【发布时间】:2012-08-26 14:56:57
【问题描述】:
大家无法从ItemSet 迭代或获取项目,以下是我的代码
物品类
public class Item {
private String id;
private int count;
private String name;
public int getcount() {
return this.count;
}
public Item(String name) {
this.name=name;
this.id = "";
}
public Item(String id, String name) {
this.name=name;
this.id=id;
}
public Item(int count) {
this.count=count;
}
public String getItemName() {
return this.name;
}
public String getItemId() {
return this.id;
}
public Item returnItems(ItemSet itemset) {
Item item=null;
return item;
}
}
ItemSet 类保存项目列表
public class ItemSet {
private List<Item> hold;
ItemSet(Item item) {
hold = new ArrayList<Item>();
this.hold.add(item);
}
ItemSet() {
//throw new UnsupportedOperationException("Not yet implemented");
}
public List<Item> getItemSet() {
return this.hold;
}
public void addItems(Item item) {
hold = new ArrayList<Item>();
this.hold.add(item);
}
}
这是我的 Transaction 类包含 ItemSets 列表
public class Transaction {
private List<ItemSet> trans;
public ItemSet getUniqueItem() {
ResultSet rs;
Database d=new Database();
ItemSet unique=new ItemSet();
String query="Select id,name from item";
rs=d.sendQuery(query);
try{
while(rs.next()) {
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
Item item=new Item(rs.getString(1),rs.getString(2));
unique.addItems(item);
}
} catch(Exception e) {
System.out.print(e.getMessage());
}
return unique;
}
}
这是我的主要课程
public class Ap {
public static void main(String args[]) {
Transaction t=new Transaction();
Transaction Ci=new Transaction();
Transaction Li=new Transaction();
ItemSet I=t.getUniqueItem(); //11
}
}
我不知道如何在 11 时从 ItemSet 中获取项目
我尝试过使用
foreach(Item i:I) {
}
但我遇到了错误。
【问题讨论】:
-
你遇到了什么错误?
-
使用“set”这个词对键的迭代具有令人困惑的含义......我会使用不同的词,但这与您的问题无关。
-
嗯,你创建了很多项目列表。就像每次添加项目一样。可能是个问题。保存
ItemSets 列表而不是只有一个列表的目的是什么? -
错误命名的“addItems”,(它需要一个项目)总是会清除现有列表并用一个包含单个项目的新列表替换它。
-
@SteveH。是的,可能是从初始化构造函数中复制/粘贴的。
标签: java