list stored set of reference data types problem

list stored set of reference data types problem

Storage elements of the set list:

(1) If the list is stored in the basic data types, the value is stored

(2) if the list is stored in the reference data types (such as object, etc.), the reference is stored

If the object reference address has not changed, content changes, can cause changes in the content of the object when calling

For example, following a stored list of objects in the collection:

  //构建原始数据
        ArrayList<Goods> list = new ArrayList();
        Goods goods1=new Goods("plum ", 2);
        list.add(goods1);
        list.add(new Goods("apple", 1));
        list.add(new Goods("banana", 2));

        //打印原始数据
        System.out.println("原始数据:");
        for(Goods goods : list){
            System.out.println(goods);
        }
        goods1.setGoodsId(444);//改变goods1的内容
        System.out.println("原始数据1:");
        for(Goods goods : list){
            System.out.println(goods);
        }

result:

原始数据:
Goods{goodsName='plum ', goodsId=2}
Goods{goodsName='apple', goodsId=1}
Goods{goodsName='banana', goodsId=2}
原始数据1:
Goods{goodsName='plum ', goodsId=444}
Goods{goodsName='apple', goodsId=1}
Goods{goodsName='banana', goodsId=2}

The results show that: Since the contents of reference referred list stored in the object has changed, resulting in a change in the content of the list of elements

Guess you like

Origin blog.51cto.com/12721734/2436419