-2

I was looking through the Java libraries and I saw this code in the Arrays.java:

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

And I am just wondering that isn't it suppose to be:

return new ArrayList<T>(a);

My guess is that it is calling this method in ArrayList.java:

public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
}

What does the question mark mean at Collection?

Bas de Groot
  • 676
  • 3
  • 16
Mireodon
  • 165
  • 1
  • 11
  • Hi! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Ask **one** question per question. Either ask what the `<>` is, or ask what the `?` is. – T.J. Crowder Nov 05 '18 at 08:25
  • 2
    Re: `<>`: https://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7 – T.J. Crowder Nov 05 '18 at 08:25
  • 2
    https://stackoverflow.com/questions/3009745/what-does-the-question-mark-in-java-generics-type-parameter-mean This may help you – Janith Udara Nov 05 '18 at 08:26
  • The `<>` feature has been around for 7 years. If it compiles and it's in the JDK it is probably right. – Peter Lawrey Nov 05 '18 at 08:34
  • 1
    They are explained in the Oracle Java Generics tutorials (Specifically: ["The Diamond"](https://docs.oracle.com/javase/tutorial/java/generics/types.html) and ["Upper Bounded Wildcards"](https://docs.oracle.com/javase/tutorial/java/generics/upperBounded.html)). May I suggest you read the whole tutorial, as it will introduce you to these and other concepts. – Andy Turner Nov 05 '18 at 08:35

1 Answers1

4

Since java 7 you can use return new ArrayList<>(a); instead of return new ArrayList<T>(a); and it will automatically add the required type. Using it as <> tells the compiler it has a type and it matches the correct one (the generics is just meta information anyway)

Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23