Aslist and ArrayList have to tell stories
Aslist and ArrayList have to tell stories
brief introduction
When it comes to collection classes, ArrayList should be used a lot. The ArrayList here is Java util. ArrayList, how do we usually create ArrayList?
Create ArrayList
Take the following example:
List<String> names = new ArrayList<>();
The above method creates an ArrayList. If we need to add elements to it, we need to call the add method again.
We usually use a more concise method to create a list:
@Test
public void testAsList(){
List<String> names = Arrays.asList("alice","bob","jack");
names.add("mark");
}
See the definition of the aslist method:
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
Good, use arrays Aslist, we can easily create ArrayList.
Run the above example. Something strange happened. The above example threw an unsupported operation exception.
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.flydean.AsListUsage.testAsList(AsListUsage.java:18)
UnsupportedOperationException
Let's talk about this exception first. Unsupported operationexception is a runtime exception, which is usually used in some methods that do not implement interfaces in some classes.
Why does the above ArrayList throw an exception when calling the add method?
asList
Let's take a closer look at arrays ArrayList returned in aslist method:
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess,java.io.Serializable
As you can see, arrays The ArrayList returned by aslist is an internal class in the arrays class, not Java util. ArrayList。
This class inherits from abstractlist. In abstractlist, the add method is defined as follows:
public void add(int index,E element) {
throw new UnsupportedOperationException();
}
Well, our problem has been solved.
transformation
We use arrays After aslist gets the ArrayList, can it be converted into Java util. What about ArrayList? The answer is yes.
Let's look at the following example:
@Test
public void testList(){
List<String> names = new ArrayList<>(Arrays.asList("alice","jack"));
names.add("mark");
}
The above example can be executed normally.