【发布时间】:2014-04-14 08:37:44
【问题描述】:
您好,我是 Java 新手,刚刚在作业中遇到以下问题。我需要编写一个类,在调用 void 方法时将新对象添加到列表中。作为提示,给出了迭代器方法的结构,所以我的代码的核心结构现在如下所示:
public class objectList implements Iterable<Obj> {
private ArrayList<Obj> objectList;
attribute_a A;
attribute_b B;
attribute_c C;
public objectList(attribute_a A, attribute_b B, attribute_c C){
objectList = new ArrayList<Obj>;
this.A = A;
this.B = B;
this.C = C;
}
public void extendList(attribute_a A, attribute_b B, attribute_c C){
objectList.add(new Obj(A,B,C));
}
public Iterator<Obj> iterator(){
return objectList.iterator();
}
@Override
public String toString(){
newstr = "";
for(i = 0;i<objectList.size();i++)
{
//Assuming Obj has the method toString()
//It prints out all details of each object, then join into one string
newstr += objectList.get(i).toString();
}
return newstr;
}
}
我被告知只使用 java.util.iterator,而不是自定义迭代器 - 所以它让我免于定义 HasNext()、next()、remove() 等。
编辑:我的目标是能够打印存储在 objectList 中的对象,在 extendList() 被调用几次之后,即列表中存储了许多项目。现在我只能打印其中的最新项目(列表中只有一项)。
如何使“光标”自动指向下一项 -> 获取属性 -> 对属性执行任务 -> 下一项等,直到列表完成?
【问题讨论】:
-
你是说你只能打印最后一个对象而不是所有添加的对象吗?这是你的问题吗?
-
你的 toString 输出是什么?
-
请给出您的问题陈述的目标或定义(您想要实现什么?)