Arrays.asList, how does it work?

I usually work with C #, so this may affect my understanding / expectation of how code should work in Java (TM).

I tried to convert a string to a hash character set, and trying to solve such a really interesting problem, I found that the following code compiles:

    Integer[] ints = new Integer[] { 1, 2, 3 };
    List<Integer> intsList = Arrays.asList(ints); // list of T


    int[] intsPrimitive = new int[] {1, 2, 3};
    List<int[]> primitiveList = Arrays.asList(intsPrimitive); // list of list of T

Fascinated, I had to try to figure out what was going on. It looks like a signature for asList:

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

hmm it looks like this is due to the way the Java (TM) compiler handles an unknown number of parameters (called "params" in C #).

, a int[] , , List<T> T=int[]? , ? , , int Object, T ( ), asList?

+4
3

(byte, short, char, int, long, float, double) Object ( T) , Java (, int long) autobox (, int Integer ), . , .

, , :

(Β§15.12.2.2) arity.

(Β§15.12.2.3) , arity.

(Β§15.12.2.4) arity, .

autoboxing int Integer:

Integer[] ints = new Integer[] { 1, 2, 3 };
List<Integer> intsList = Arrays.asList(ints);

int[] , , Object signature Arrays.asList(Object...), Java:

int[] intsPrimitive = new int[] {1, 2, 3};
List<int[]> primitiveList = Arrays.asList(intsPrimitive);
0

, , .

, , Arrays.asList, , , ArrayList, . , .

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

-, ArrayList , . int , .

// Your ints are boxed in this form...
List<Integer> intList = Arrays.asList(1, 2, 3);
// ...and in this form...
Integer[] ints = new Integer[] {1, 2, 3};
List<Integer> intList = Arrays.asList(ints);
// ...but not in this form.
int[] ints = new int[] {1, 2, 3};
List<int[]> intOfIntsList = Arrays.asList(ints);

-, , . , int[] is-an Object. , ( ):

Object foo = new int[10];

, int[] , , - , , .

, Java . , Java, 4.5.1, :

, . Wildcards , .

TypeArguments:
< TypeArgumentList >
TypeArgumentList:
TypeArgument {, TypeArgument}
TypeArgument:
ReferenceType 
Wildcard
Wildcard:
{Annotation} ? [WildcardBounds]
WildcardBounds:
extends ReferenceType 
super ReferenceType

, , , .

0

, . , .

Arrays.asList(T... a) varargs, . A varargs , T.

T Object, , Java Generics (. asList),, int. , int [], Object, int [].

+1 .

0

Source: https://habr.com/ru/post/1695365/


All Articles