Hello friends, As i said i am here with "How to use our own class object in enhanced for loop". As we seen we can use collection classes object in enhanced for loop because root (super) interface for all collection classes is java.lang.Iterable. So same as we also have to create a class with implementing java.lang.Iterable. So lets create a class:
public class Custom implements Iterable{ }
Now we have to override only one available method of Iterable interface that is iterator();
@Override
public Iterator iterator() {}
public Iterator iterator() {}
Now we have to create an object of class that implements java.util.Iterator interface. And we have to return this object from iterator() method. Here i am going to create an anonymous inner class. But before doing this we have to create decide that what type of data we wants to return from our class object? and how many data? Here for example i am taking an String array:
private String []data={
"first data",
"second data",
"third data",
"fourth data"
};
private int index=-1,size=data.length;
private int index=-1,size=data.length;
new Iterator() {
@Override
public boolean hasNext() {
return ++index < size;
}
@Override
public boolean hasNext() {
return ++index < size;
}
@Override
public String next() {
return data[index];
}
public String next() {
return data[index];
}
@Override
public void remove() {
size--;
}
};
public void remove() {
size--;
}
};
Custom cust=new Custom();
for(Object s: cust){
System.out.println(s);
}
for(Object s: cust){
System.out.println(s);
}
Here the full code of custom class and test class with output:
Here an example with generics:
I hope it is helpful for you all. So be Java Lover and keep reading...
You can also watch my video on you-tube about enhance for loop. Watch now
No comments:
Post a Comment