Sự khác biệt giữa List.of và Arrays.asList là gì?

Arrays.asListtrả về một danh sách có thể thay đổi trong khi danh sách được trả về List.oflà không thay đổi :

List<Integer> list = Arrays.asList(1, 2, null);list.set(1, 10); // OK List<Integer> list = List.of(1, 2, 3);list.set(1, 10); // Fails with UnsupportedOperationException

Arrays.asListcho phép các phần tử null trong khi List.ofkhông:

List<Integer> list = Arrays.asList(1, 2, null); // OKList<Integer> list = List.of(1, 2, null); // Fails with NullPointerException

contains cư xử khác với null

List<Integer> list = Arrays.asList(1, 2, 3);list.contains(null); // Returns false List<Integer> list = List.of(1, 2, 3);list.contains(null); // Fails with NullPointerException

Arrays.asListtrả về một khung nhìn của mảng đã qua, vì vậy những thay đổi đối với mảng cũng sẽ được phản ánh trong danh sách. Đối với List.ofđiều này là không đúng sự thật:

Integer[] array = {1,2,3};List<Integer> list = Arrays.asList(array);array[1] = 10;System.out.println(list); // Prints [1, 10, 3] Integer[] array = {1,2,3};List<Integer> list = List.of(array);array[1] = 10;System.out.println(list); // Prints [1, 2, 3]

Sliding Sidebar

About Me

About Me

Hello, my name is Dũng (Johnny). Welcome to my blog.

As I’m a developer, I write about topics related to the field of programming, mainly from a technical point of view. On this blog you’ll find posts which encourage discussion, information about development trends, case studies, reviews, tutorials, tips on how to improve your effectiveness, and anything else that might be fascinating to people from the IT industry.
I love PHP, NodeJS, Java,... and Fullstack.