doc says Collections.singletonList is immutable so i test about Arrays.asList and Collections.singletonsList.
First Test
List<Student> asList = Arrays.asList(new Student(10)); Student student = asList.get(0); student.setAge(20); System.out.println(asList); // 20 List<Student> singletonList = Collections.singletonList(new Student(10)); Student student1 = singletonList.get(0); student1.setAge(20); System.out.println(singletonList); // 20
it is not immutable.
Second Test
List<Student> asList = Arrays.asList(new Student(10)); Student student = asList.get(0); student = null; System.out.println(asList); // 10 List<Student> singletonList = Collections.singletonList(new Student(10)); Student student1 = singletonList.get(0); student1 = null; System.out.println(singletonList) ; // 10
can not change reference.
Third Test
List<Student> asList = Arrays.asList(new Student(10)); asList.remove(0); // UnsupportedOperationException List<Student> singletonList = Collections.singletonList(new Student(10)); singletonList.remove(0); // UnsupportedOperationException
so what is difference??
https://stackoverflow.com/questions/65433098/arrays-aslist-vs-collections-singletonslist-about-immutable-in-java December 24, 2020 at 09:58AM
没有评论:
发表评论