The advantages of utilizing an iterator is to permit the the consumer to iterate over the gathering of objects, with out exposing implementation particulars. This provides you the profit to vary what assortment the Iterator iterates over and the way every aspect is served, with out making any change the consumer’s code. To iterate a customized assortment, class have to implements Iterable
interface.
A category that implements the Iterable can be utilized with the brand new for-loop. Right here is such an instance:
1
2
3
4
|
Listing record = new ArrayList();
for(Object o : record){
//do one thing o;
}
|
The Iterable interface has just one technique:
1
2
3
|
public interface Iterable<T> {
public Iterator<T> iterator();
}
|
Now create a java class so as to add into that ArrayList
…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
bundle org.techzoo.util;
import static java.lang.String.format;
public class Pencil {
personal String identify,make;
personal int value;
public Pencil(){}
public Pencil(String identify,String make,int value){
this.identify = identify;
this.make = make;
this.value = value;
}
public String getName() {return identify;}
public String getMake() {return make;}
public int getPrice() {return value;}
public void setName(String identify) {this.identify = identify;}
public void setMake(String make) {this.make = make;}
public void setPrice(int value) {this.value = value;}
@Override
public String toString(){
return format(“Title:tpercentstMake:tpercentstPrice:tpercentd”,
identify,make,value);
}
}
|
Now, create a category PencilArrayList
which implements Iterable
interface.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
bundle org.techzoo.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Listing;
public class PencilArrayList implements Iterable<Pencil> {
personal Listing<Pencil> pencils;
personal static ultimate int MIN_SIZE = 10;
public PencilArrayList(){
pencils = new ArrayList<Pencil>(MIN_SIZE);
}
public PencilArrayList(int dimension){
pencils = new ArrayList<Pencil>(dimension);
}
public void addPencil(Pencil p){
pencils.add(p);
}
public void removePencil(Pencil p){
pencils.take away(p);
}
public int dimension(){
return pencils.dimension();
}
@Override
public Iterator<Pencil> iterator() {
return pencils.iterator();
}
public static void essential(String[] args) {
Pencil p1 = new Pencil(“SuperB”,“Natraj”,3);
Pencil p2 = new Pencil(“Hero”,“Swami”,4);
PencilArrayList pList = new PencilArrayList();
pList.addPencil(p1);
pList.addPencil(p2);
for (Pencil pencil : pList) {
System.out.println(pencil);
}
}
}
|
Supply techzoo.org