Java single instance, attribute sharing

java instance implements property sharing. For example, I now have a 10 million-word loop, and I need to change the property in an instance to I

.

the code is as follows

List<OrderInfo> orderInfos = new ArrayList<OrderInfo>();
OrderInfo orderInfo=null;
for(int i=0;i<10000000;iPP){
    orderInfo = new OrderInfo();
    orderInfo.setOrderState(i);
    orderInfos.add(orderInfo);
}

if orderInfo is mentioned, an object will be referenced

orderInfo = new OrderInfo();
for(int i=0;i<10000000;iPP){
    orderInfo.setOrderState(i);
    orderInfos.add(orderInfo);
}

the problem is very simple. If the attributes in my object are very complex and heavy, then the rest of the attributes are wasted . Is there any way to share other attributes and be independent of orderState, which can save a lot of memory? please give us some advice when entering java, for the first time. Thank you

.
Mar.21,2021

static or by wrapping one layer.

for(int i=0;i<10000000;iPP){
    OrderInfoWrapper orderWrapper = new OrderInfoWrapper(i, orderInfo);
}

class OrderInfoWrapper {
    int i;
    OrderInfo orderInfo;
}

static , static variable, check it out.


decorate the properties that need to be shared with static.


shared properties have thread safety problems, which need to be noted!

Menu