如何获取对象';Java列表中的索引
我正在尝试将数据添加到数组列表中。在这个结果中如何获取对象';Java列表中的索引,java,arraylist,json,Java,Arraylist,Json,我正在尝试将数据添加到数组列表中。在这个结果中 [{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 s
[{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);
我需要获取数组列表中对象的索引。问题是,我无法循环“获取对象存储和对象产品”的数组列表并找到每个索引。。什么是最有效的解决方案?好的,您可以使用List.indexOf(),正如其他人所建议的: 如果您计划经常这样做,那么您大概有一个对象引用的句柄。因此,您可以扩展/包装您希望的索引跟踪其自身索引的对象。具体地说,您可以根据第一次遇到对象的顺序或其他情况为对象指定索引。然后,集合中对象的顺序将不相关 我想你也可以使用地图作为另一种可能性。然后仅使用映射而不是ArrayList
一句话:如果您正在执行大量的“indexOf()”请求,那么ArrayList可能不是存储数据的最佳容器。当您应该编写一个类来保存这些数据时,为什么在这里使用
Map
s?为什么不能循环查看ArrayList
?(最后,为什么不使用泛型,这将使代码更具可读性?)查找List.indexOf(Object)??请注意,indexOf方法可能仍在数组中迭代,因此如果关注的是性能,indexOf运算符可能不会为您买任何东西。评论的情绪是好的——总是尝试选择数据结构来支持您的需求,而不是寻找一种方法来补偿错误的数据结构。