[英]How do I access these Elements of a class using Iterator?
I have two classes: Question
and Answers
. 我有两节课:
Question
和Answers
。 The Answer
class has its own attributes. Answer
类具有其自己的属性。 I passed 2 Lists of arguments to Answers
using Constructor-Injection (Spring framework). 我使用Constructor-Injection(Spring框架)将2个参数列表传递给
Answers
。
I want to iterate to display only the id of the Answer attribute. 我想迭代以仅显示Answer属性的ID。 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
. 当前代码显示答案类中的每个属性,即
id
, name
, postedby
。
On the place where you make Iterator 在制作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. 现在,当您调用itr.next()时,它将为您提供Answers对象。 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);
You desire can be fulfilled by this: 您的愿望可以通过以下方式实现:
1.Change your toString
method to just return id
; 1.将您的
toString
方法更改为仅返回id
;
2.Print only id
in collection: 2.仅打印集合中的
id
:
Iterator<Answer> itr = answers.iterator();
while(itr.hasNext()) {
System.out.print("\n"+itr.next().id);
}
Use enhanced for loops to make your code clearer and more easily maintainable: 使用增强的for循环可以使代码更清晰,更易于维护:
for (Answers answer : answers) {
System.out.print("\n" + answer.id);
}
If you let System.out.print("\\n" + answer);
如果让
System.out.print("\\n" + answer);
, the toString()
of your class Answers
(which includes all fields) will be called. ,则将调用类
Answers
(包括所有字段)的toString()
。 You can also change Answers.toString()
to only include the id. 您也可以将
Answers.toString()
更改为仅包含ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.