2012-12-07 30 views
2

我試圖將數據添加到數組列表中。在這個結果如何獲取Java列表中的對象索引

[{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); 

我需要得到一個對象的索引的數組列表。問題是,我無法循環訪問「獲取對象存儲和對象產品」的數組列表,並找到每個索引。什麼是最佳的有效解決方案?

+3

爲什麼你在這裏使用'Map',當你應該寫一個類來保存這些數據?並且_why_不能循環訪問'ArrayList'嗎? (最後,爲什麼不使用泛型,這會讓你的代碼更具可讀性?) –

+1

尋找List.indexOf(Object)? – PermGenError

+1

['ArrayList'有一個'indexOf'方法](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object))。 –

回答

1

嗯,你可以使用List.indexOf(),如其他人所說:

Java List API: indexOf()

如果您打算在此做了很多,那麼想必你對你的對象引用的句柄。所以,你可以擴展/包裝你想要索引的對象來跟蹤它自己的索引。具體而言,您可以根據您第一次遇到它的順序或某物,將Object索引分配給它。然後集合中的對象的順序將不相關。

我想你也可以使用地圖作爲另一種可能性。然後只能使用Map而不是ArrayList。底線:如果你做了很多「indexOf()」請求,那麼ArrayList可能不是你數據的最佳容器。

相關問題