【发布时间】:2012-11-25 23:37:45
【问题描述】:
我正在尝试将数据添加到数组列表中。在这个结果中
[{Store={id_store=2, namestore=Kupat Tahu Singaparna , product=[{id_product=1, price=100000, quantity=1}]}}]
您可以使用以下代码:
static ArrayList Storecart = new ArrayList();
LinkedHashMap store = new LinkedHashMap();
LinkedHashMap storeitem = new LinkedHashMap();
LinkedHashMap listproduct = new LinkedHashMap();
ArrayList prdct = new ArrayList();
storeitem.put("id_store",id_store);
storeitem.put("namestore",namestr );
listproduct.put("id_product", id_prodt);
listproduct.put("price",priced);
listproduct.put("quantity", quantity);
prdct.add(listproduct);
storeitem.put("product", prdct);
store.put("Store", storeitem);
Storecart.add(store);
我需要在数组列表中获取一个对象的索引。问题是,我无法为“获取对象存储和对象产品”循环数组列表并找到每个索引。什么是最好和有效的解决方案?
【问题讨论】:
-
你为什么在这里使用
Maps,而你应该编写一个类来保存这些数据? 为什么你不能循环通过ArrayList? (最后,你为什么不使用泛型,这会让你的代码更易读?) -
寻找 List.indexOf(Object) ??
-
请注意,indexOf 方法可能仍会遍历数组,因此如果关注的是性能,则 indexOf 运算符可能不会给您带来任何好处。 cmets 的观点是好的——总是尽量选择你的数据结构来支持你的需求,而不是寻找一种方法来补偿错误的数据结构。