The method of conversion between an array and a List

  • 2020-04-01 02:24:07
  • OfStack

1.List is converted into an array. (the List here is an ArrayList.)
The toArray method of ArrayList is called.

toArray

Public T[] toArray(T[] a) returns an array containing all the elements in the list in the correct order. The runtime type of the returned array is the runtime type of the specified array. If the list can fit into the specified array, returns the array of elements that fit into the list. Otherwise, a new array is assigned based on the run-time type of the specified array and the size of the list.

If the specified array can hold the list and has space left (that is, there are more elements in the array than in the list), then the element immediately following the collection in the array is set to null. This is useful for determining the length of the list, but only if the caller knows that the list does not contain any null elements.

Specify:

ToArray in the interface Collection

Specify:

ToArray in the interface List

Cover:

ToArray in the AbstractCollection class

Parameters:

A - an array of list elements to store, if it is large enough; Otherwise, it is a new array with the same run-time type allocated for storing list elements.

Returns:

An array containing list elements.

Throws:

ArrayStoreException - if the runtime type of a is not the supertype of the runtime type of each element in this list.
Specific usage:


List list = new ArrayList(); 
list.add("1"); 
list.add("2"); 
final int size = list.size(); 
String[] arr = (String[])list.toArray(new String[size]);

2. Convert the array to List
The asList method of Arrays is called.

JDK 1.4 defines java.util. arrays. asList with the function parameter Object[]. Therefore, in 1.4, asList() does not support arrays of primitive types as arguments.

In JDK 1.5, the definition of java.util.arrays.aslist, with Varargs as the function parameter, adopts a generic implementation. Thanks to autoboxing, it also supports arrays of objects and primitive types.

However, in use, when passing in an array of basic data types, there will be a small problem. The entire array passed in will be treated as the first element in the returned List, for example:


public static void main(String[] args){
    int[] a1 = new int[]{1,2,3};
    String[] a2 = new String[]{"a","b","c"};

    System.out.println(Arrays.asList(a1));
    System.out.println(Arrays.asList(a2));
}

1. The printed results are as follows:

1
2 [[I@dc8569]
[a, b, c] 

Here is the return value of arrays.aslist () :

Here's what the JDK documentation says:
Public static < T> List< T> AsList (T... A) returns a fixed-size list supported by the specified array. Changes to the returned list are "written directly" to the array. This approach, along with collection.toarray (), ACTS as a bridge between the array-based API and the collection-based API. The returned list is serializable, and RandomAccess is implemented. This method also provides a convenient way to create a fixed-length list of columns



 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;
     }

     public int size() {
        return a.length;
     }

     public Object[] toArray() {
        return a.clone();
     }

     public <T> T[] toArray(T[] a) {
         int size = size();
         if (a.length < size)
            return Arrays.copyOf(this.a, size, (Class<? extends T[]>) a.getClass());
         System.arraycopy(this.a,0, a, 0, size);
         if (a.length > size)
            a[size] = null;
         return a;
     }

     public E get(int index) {
        return a[index];
     }

     public E set(int index, E element) {
         E oldValue = a[index];
         a[index] = element;
         return oldValue;
     }

     public int indexOf(Object o) {
         if (o == null) {
             for (int i = 0; i < a.length; i++)
             if (a[i] == null)
             return i;
         }else {
             for (int i = 0; i < a.length; i++)
             if (o.equals(a[i]))
             return i;
         }
         return -1;
     }

     public boolean contains(Object o) {
        return indexOf(o) != -1;
     }
}

The table is initialized to contain multiple elements: List< String> Stooges = Arrays. AsList ("Larry", "Moe", "Curly");
As we all know, a typical feature of a List is that its length is variable. We can easily insert and delete elements into it. Using arrays.aslist (array) returns a List that does not support add and remove operations.

What's the reason?

Arrays.aslist source code:


1
2
3 public static <T> List<T> asList(T... a) {
   return new ArrayList<T>(a);
} 

The ArrayList here is not the java.util.ArrayList, but the inner class of Arrays:

We can see that the inner class inherits AbstractList, and here is the source code for AbstractList's add and remove methods:


public boolean add(E e) {
    add(size(), e);
    return true;
}

public void add(int index, E element) {
    throw new UnsupportedOperationException();
}

public E remove(int index) {
    throw new UnsupportedOperationException();
}

. So, when we are on the Arrays asList returned when add or delete the List will be submitted to the Java lang. UnsupportedOperationException anomalies.


Related articles: