简体   繁体   中英

Object HashMap memory/reference issue

I have a for each loop iterating in a list. I add a object to another Object list then i modify the value of the object then I add to another list.

Problem is first list value also changed after modifying the object before adding to the second list.

I am facing this type of reference/memory issue all over the project. In previous, i faced memory/reference issue even if i use new Keyword / addAll() etc method to copy list data.

orderListNormal = new HashMap<>();
orderListDelete = new HashMap<>();
orderListExtra = new HashMap<>();

for (Integer hashcode :
                salesOrderList.keySet()) {

            OrderSalesModel order = salesOrderList.get(hashcode);

            if (order.getQuantityAvailable() == 0) {
                if (isDirectOrder) {
                    processOrderListener.invalidQuantity();
                    return;
                }
                double regular = order.getQuantity();
                double extra = order.getQuantity() - order.getQuantityAvailable();
                regular = regular - extra;

                order.setQuantity(regular);
                orderListNormal.remove(hashcode);
                orderListDelete.put(hashcode, order);

                order.setOrderDetailID("0");
                order.setQuantity(extra);
                orderListExtra.put(hashcode, order);

            }
    ......
    }

You should create a new OrderSalesModel if you don't want to mutate it. Since you are holding the reference by getting the OrderSalesModel with salesOrderList.get(hashcode) you will always mutate it. Make a copy constuctor and use it like this

OrderSalesModel order = new OrderSalesModel(salesOrderList.get(hashcode));

You must clone your object. When you do:

A a = new A();
A b = a;

In fact both a and b has the same adresse when you change a , b will be changed. You must use Clone to duplicate and object in Java Take a look at this Tuto .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM