'Why it is possible to create collection of array of primitives but not collection of primitives
Java does not support creating a collection out of primitives, so following construct gives compilation error ("The argument can not be of primitive type):
List<int> ints = new ArrayList<int>();
On the other hand creating a collection of arrays or primitives is allowed, so following construct is ok:
List<int[]> ints = new ArrayList<int[]>();
What is a logic behind this?
Edit: The question is really about the array of primitives, not the primitives, so please don't explain me why can't I store primitives in collection, but rather why can I story array of primitives inside a collection?
Solution 1:[1]
Collections are generic: Collection<T>. T must be reference type. Primitives aren't reference types. On the other hand, array of primitives is a reference type so you can put it to Collection. Remember, that every primitive has it's wrapper class which can be passed as a type to generic type.
According to the specification:
Type:
PrimitiveType
ReferenceType
A class is generic if it declares one or more type variables (ยง4.4).
#
4.3.1. Objects An object is a class instance or an array.
#
4.4. Type Variables A type variable is an unqualified identifier used as a type in class, interface, method, and constructor bodies.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
