前言
今天逛了下论坛,发现有一种说法,集合不能存储基本类型,都是存储对象,我自己实验了下,List<int>报错了,而List<Integer>则通过了编译。行吧,暂且认同这种说法。
本篇主要是说明集合中存入对象的问题。对象存入集合都是以内存地址的形式存入,当存入之后,修改了对象的值,就算没有直接操作对象,那么对象里的值也会改变。
案例1
List中存入Map集合对象,可以通过直接操作Map对象,来修改已存入List的数据。
List<Map> lista = new ArrayList<>(); Map<String, String> Mapb = new HashMap<String, String>(); Mapb.put("1", "1"); lista.add(Mapb); System.out.println(lista); Mapb.put("2", "2"); lista.add(Mapb); System.out.println(lista);
输出
[{1=1}] [{2=2, 1=1}, {2=2, 1=1}]
案例2
这次实验了String类型,似乎不可以通过对象修改集合里的值。
List<String> listc = new ArrayList<>(); String str = "!"; listc.add(str); System.out.println(listc); str="?"; System.out.println(listc);输出
[!] [!]
案例3
在Map集合中存放List集合,同样可以通过直接操作List集合来修改Map中的值。
Map<String, List> Maps = new HashMap<String, List>(); List<String> lists = new ArrayList<>(); lists.add("1"); Maps.put("222", lists); System.out.println(Maps); lists.add("2"); System.out.println(Maps);
输出
{222=[1]} {222=[1, 2]}
案例4
在List为CC对象的类型中,通过直接修改CC对象,可以修改List值。
List<cc> listsc = new ArrayList<>(); cc acca = new cc(1 , "123"); listsc.add(acca); System.out.println(listsc); acca.setID(2); System.out.println(listsc);输出
[cc [ID=1, Name=123]] [cc [ID=2, Name=123]]