EDIT: forgot a line of code that is likely causing the issue (night’s sleep helped 😉
Ok it’s late so I’m probably missing something fundamental here but this is my issue:
I have query my db and get a data set that looks like this:
retail_store_id basket_item_id price_txt 1 2 8.99 1 1 1.5 1 6 11.09 1 4 3.99 2 6 10.99 2 2 9 2 1 1.79 3 4 2.99 3 1 1.5 4 1 1.39 4 6 9.99 4 4 3.5 4 2 7.99
Now I have a Store class which contains a List items and each basketitem has a price.
now to get that into my dto’s I do this:
Map<Integer, Store> shoppedBasketHash = new HashMap<Integer, Store>();
while (rs.next()){
int storeID = rs.getInt("retail_store_id");
basketItem = new BasketItem();
basketItem = GlobalHashOfItems.get(rs.getInt("basket_item_id"));
basketItem.price = new BigDecimal(rs.getString("price_txt"));
if(shoppedBasketHash.containsKey(storeID)){
shoppedBasketHash.get(storeID).items.add(basketItem);
}else{
Store store = new Store();
store.retailStoreID = rs.getInt("retail_store_id");
store.items = new ArrayList<BasketItem>();
store.items.add(basketItem);
shoppedBasketHash.put(storeID, sb);
}
}
return new ArrayList<Store>(shoppedBasketHash.values());
Now for some reason, later on when I take this list:
for(Store s: listOfStores){
for(BasketItem b: s.items){
System.out.println(b.price);
}
}
I get this:
9.99
3.5
7.99
1.39
1.39
9.99
7.99
1.39
3.5
3.5
7.99
1.39
9.99
Which is not the same list of prices I took in. What am I doing wrong?
I realize now the issue is in the
basketItem = GlobalHashOfItems.get(rs.getInt(“basket_item_id”));
I have a hash of items (without prices) that contains other item info not pulled from the DB that I need to use then add the price too. But it’s not copying by value it’s using an object reference. How do I make basketItem get assigned to the value of the GlobalHashOfItems item and not a reference?
Your problem is that
HashMapdoes not preserve insertion/iteration order when it is converted into anArrayListto return from your method.You can solve this by building the
ArrayListto return while using theMapfor addition.Another way would be to use a LinkedHashMap which does preserve insertion/iteration order.