简体   繁体   中英

If Java doesn't support parameterized type arrays, how does Arrays.asList() work with them?

Supposedly, the method Arrays.asList looks like this:

public static <T> List<T> asList(T... a)

T... is practically equivalent to T[] , but aren't arrays of generic types disallowed in Java? For example:

// Example 1
ArrayList<Integer>[] list = new ArrayList<Integer>[10];  // This is not allowed

// Example 2
List<ArrayList<Integer> > listOfList = Arrays.asList(new ArrayList<Integer>(), new ArrayList<Integer>());  // Allowed?

In example 2, the two parameters I passed would imply that Arrays.asList is taking ArrayList<Integer>[] as parameters which contradicts example 1. Why does example 2 work when example 1 doesn't?

You can declare ageneric type array in Java which is perfectly legal. So this should work.

private E[] array;

But you can't instantiate a generic array like so, because arrays are reified and all the generic types are implemented as erasure. So this fictitious E is not available at runtime and you are out of luck !

array = new E[10];  // Illegal and gives compiler error.

But you have a workaround here. What you can do it just a cast.

array = (E[]) new Object[10];

This way you can create and instantiate a generic array in java. You may use @SuppressWarnings("unchecked") at the lowest possible level, may be at the site of declaration to get rid of any unchecked warnings made by the compiler.

Here, the T[] is in a parameter declaration, and as @Ravindra Ranwala answered, declaring a variable or parameter of type T[] is perfectly fine. It's creating an array of a type parameter type, ie new T[] that is not allowed.

In this case, by passing to the varargs argument, the compiler is actually implicitly creating an array of type ArrayList<Integer>[] to pass to the method. As you know, creating an array of a parameterized type, ie new ArrayList<Integer>[] , is also not allowed. So the compiler creates new ArrayList[] , and, normally, you would get a warning in a call such as this. However, you don't get a warning in this call because Arrays.asList() has the @SafeVarargs annotation, which indicates that they do not use the runtime component type of the array object, so it is safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM