Why can primitives not be stored in Java collections, but primitive arrays can? -


list<int> list; //compile-time error list<int[]> list1; //works fine 

is there reason behavior? know primitives need boxed why not primitive arrays?

because java arrays objects, not primitives. , can store references objects in java collections implemented generic types.

from java language specification, chapter 10: arrays:

in java programming language, arrays objects (§4.3.1), dynamically created, , may assigned variables of type object (§4.3.2). methods of class object may invoked on array.

note arrays , generics don't play together. although can create collection of arrays, can't create array of collections. type-checking of array contents performed @ run time. parameterized types of collections not known @ run time, because of type erasure. joshua bloch's "effective java," 2nd ed., "item 25: prefer lists arrays":

for example, illegal create array of generic type, parameterized type, or type parameter. none of these array creation expressions legal: new list<e>[], new list<string>[], new e[]. result in generic array creation errors @ compile time.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -