1 intro
Public Static void Main(string[] args) {string[] Sarray = {"a","B","C","D","E"}; List<string> sList = Arrays.aslist(Sarray);//Modify List to see the value of ArraySList.Set(3,"CD"); System. out.println(sarray[3]);//Modify Array to see the value of Listsarray[0] ="0a"; System. out.println(SList.Get(0));//Add elements to listSList.Add("F");}
Results:
cdException in thread "main" java.lang.UnsupportedOperationException0a at java.util.AbstractList.add(AbstractList.java:148) at java.util.AbstractList.add(AbstractList.java:108) at com.wdk.scm.schedule.controller.ScmCommonController.main
Why is the error and output cd,0a? The main reason is still arrays.aslist (Sarray), looking at its source code, found:
publicstaticasList(T... a) { returnnew ArrayList<>(a);}
The return is indeed a ArrayList instance, but this ArrayList is a bit different, it is a privatized static inner class of the arrays class, not the ArrayList under the Java.util package we are usually familiar with.
constructor function:
ArrayList(E[] array) { a = Objects.requireNonNull(array);}
New was not created, but the original array reference was re-passed to a new reference a. In other words, there is only the original array in memory, and no new objects are created. Its set and get are operations on the data, and it does not rewrite the Add method, so the last add, in fact, is called Abstractlist's add
publicbooleanadd(E e) { add(size(), e); returntrue;}publicvoidadd(int index, E element) { thrownew UnsupportedOperationException();}
There is one more question:
int [] ints = {12345};List list = Arrays.asList(ints);System.out.println(list.size());
The result of the above code output is: 1
Why not 5? We're still looking at Arrays.aslist's code.
publicstaticasList(T... a) { returnnew ArrayList<>(a);}
Passed is a parameterized list, and we pass here is int[], the basic data type int is not a specific object T, so here's a is actually an array object ints!
System.out.println("list.get(0) == ints:" + list.get(0).equals(ints));
Output Result:
list.get(0) == ints:true
It is also said that the first element of the list is an array. If we change int[] to integer[]:
Integer [] ints = {12345};List list = Arrays.asList(ints);System.out.println(list.size());System.out.println("list.get(0) == ints:" + list.get(0).equals(ints));System.out.println(list.get(0));
Output Result:
5list.get(0) == ints:false1
An Integer is a data object compared to Int,integer, and can be used as a generic parameter.
Therefore, the use of arrays.aslist is not to use the basic data type as a parameter.
The hole in Java's arrays.aslist