0

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;
}
asked Apr 15, 2016 at 17:51

2 Answers 2

3

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());
}
answered Apr 15, 2016 at 17:54
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, now it works. i didn't know that i can supply Reiter as a type argument.
1

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()); 
answered Apr 15, 2016 at 17:53

3 Comments

A raw Iterator returns Objects, so the getA() method won't be available.
You're right I didn't pay attention to the lack of generics/casting
Still thanks, it helped a lot. Won't make that mistake again.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.