Array to a set of stepped pit

An array into a List object, generally thought Arrays.asList () method, which returns an object of type ArrayList. But add and delete update the list with this object, it will be reported UnsupportedOperationException exception.

public static < T > List < T > asList ( T ... A ) { return new new ArrayList < T > ( A ); }            


This is not java.util.ArrayList ArrayList class class, but the class Arrays static inner class!

public class Arrays {     .......     private static class ArrayList<E> extends AbstractList<E>         implements RandomAccess, java.io.Serializable      {         private static final long serialVersionUID = -2764017481108945198L;         private final E[] a;         ArrayList(E[] array) {          if (array==null)             throw new NullPointerException();          a = array;         }                  ......     } }


Look at this static inner class storage array elements of a variable is the final type Judging from the static inner classes do not add delete any internal elements of the operation! Just like the String class, variable String object stores an array of characters also have the final modifier. Because once the increased array element, the array capacity has given good container will not be able to load the added element.

Internal class which did not add, remove method, this class inherits AbstractList class there are these methods.

 

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { ........ public void add(int index, E element) { throw new UnsupportedOperationException(); } public E remove(int index) { throw new UnsupportedOperationException(); } }



Can be seen, AbstractList the add and remove methods defined in the abstract class, just throw an exception! Why is not defined as an abstract way to do that? Then let the implementation class to achieve.

So, if you want to convert an array into a list and do increase the delete operation, it is recommended the following code:

 

List<WaiterLevel> levelList = new ArrayList<WaiterLevel>(Arrays.asList("a", "b", "c"));

Guess you like

Origin www.cnblogs.com/wwwbin/p/11358334.html