i wanted to print the A (getA()) of the Object Reiter with the iterator, but i don't seem to find anything that works. Could you help somehow please.
public static void main (String args[]){
LinkedList<Reiter> reiter = new LinkedList<Reiter>();
reiter.add(new Reiter(55));
reiter.add(new Reiter(30));
reiter.add(new Reiter(70));
reiter.add(new Reiter(35));
reiter.add(new Reiter(60));
reiter.add(new Reiter(45));
reiter.add(new Reiter(65));
reiter.add(new Reiter(40));
reiter.add(new Reiter(25));
reiter.add(new Reiter(50));
Iterator it = reiter.iterator();
while(it.hasNext()){
System.out.print(it.next());
}
}
class Reiter{
int a;
public Reiter(int a){
this.a = a;
}
public int getA(){
return a;
}
2 Answers 2
You are using the raw form of Iterator, which will return Objects. You can use the pre-Java 1.5 solution -- cast the returned object to a Reiter -- or you can use the generic form of Iterator, supplying Reiter as a type argument to Iterator.
Iterator<Reiter> it = reiter.iterator();
This will allow you to treat the returned object as a Reiter and call getA().
while(it.hasNext()){
System.out.print(it.next().getA());
}
In your while loop:
while(it.hasNext()){
System.out.print(it.next());
}
You need to print it.next().getA();
Simply printing the it.next() will print the object.
So the line should change to
System.out.print(it.next().getA());
3 Comments
Iterator returns Objects, so the getA() method won't be available.