Reputation: 427
Hi I am stuck at how to iterate through a generic list using iterator.
for example i hve something like this:
public class a{
protected int _b;
protected String _c;
protected float _d;
protected int _e;
public a(int b, String c, float d, int e){
// assign value _b,_c,_d,_e
}
static class ab implement Iterable<a>{
public static List myList = new ArrayList(a);
public static void addlist(a f){
myList.add(f);
public Iterator<a> iterator(){
return myList.iterator()}// overriding List iterator method
then in main method i assign value for _b,_c,_d,_e by creating instances of class a and add it to myList but when i use the iterator it doesnt show the list but it shows the memory location( i guess)of that list. I want it to show all the field in class a one by one. any suggestion what i should do ???
Upvotes: 0
Views: 510
Reputation: 49372
Override the toString()
method in Class a
.
@Override
public String toString() {
return "_b:"+_b+",_c:"+_c+"_d:"+_d+",_e:"+_e;
}
If toString()
is not overridden then , your Class a
uses the inherited one from Class Object
:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Upvotes: 1
Reputation: 27346
it doesnt show the list but it shows the memory location( i guess)of that list.
.
It is showing the memory location because you have not overridden the toString
method, so it is falling back on the default Object
implementation. You need to override the toString
method in your a
class.
If you add something like:
public String toString()
{
return // Some string data.
}
To your a
class, you'll start seeing correct outputs.
Note: Java naming convention states that all classes should start with a capital letter, and have a capital letter for every word. ie: a -> A
.
Upvotes: 2