qwerty
qwerty

Reputation: 21

How do I access these Elements of a class using Iterator?

I have two classes: Question and Answers. The Answer class has its own attributes. I passed 2 Lists of arguments to Answers using Constructor-Injection (Spring framework).

I want to iterate to display only the id of the Answer attribute. Is that possible ?

package Question.Answer;

public class Answers {
String id;
String name;
String by;
     public Answers(String id,String name,String by) {
        super();
        this.id = id;
        this.name = name;
        this.by = by;
    }
    public String toString() {
        return "id:"+id+"name:"+name+"Posted by"+by;
    }
}

Question Class

package Question.Answer;
import java.util.Iterator;
import java.util.List;
public class Question {
    private String name;
    private String id;
    private List<Answers> answers;
    public Question(String name,String id,List<Answers> answers) {
        this.name = name;
        this.id = id;
        this.answers = answers;
    }
    public void display() {
        System.out.println("Name:\t"+name+"\nid:\t"+id);
        Iterator itr = answers.iterator();
        while(itr.hasNext())
            System.out.print("\n"+itr.next());
    }
}

The present code displays every attribute in answer class ie id, name, postedby.

Upvotes: 1

Views: 103

Answers (3)

Level_Up
Level_Up

Reputation: 824

On the place where you make Iterator

Iterator itr = answers.iterator();

please add type like this:

Iterator<Answers> itr = answers.iterator();

Now when you call itr.next() it will give you Answers object. Just to be more clear add this rows on the place of

System.out.print("\n"+itr.next());

Please replace with:

Answers answer = itr.next();
System.out.print("\n" + answer.id);

Upvotes: 3

Adam Ostrožl&#237;k
Adam Ostrožl&#237;k

Reputation: 1416

You desire can be fulfilled by this:

1.Change your toString method to just return id;

2.Print only id in collection:

Iterator<Answer> itr = answers.iterator();
while(itr.hasNext()) {
    System.out.print("\n"+itr.next().id);
}

Upvotes: 1

Alex M
Alex M

Reputation: 915

Use enhanced for loops to make your code clearer and more easily maintainable:

for (Answers answer : answers) {
    System.out.print("\n" + answer.id);
}

If you let System.out.print("\n" + answer);, the toString() of your class Answers (which includes all fields) will be called. You can also change Answers.toString() to only include the id.

Upvotes: 0

Related Questions