1

In Java inside the angle brackets <> for collections we are supposed to provide the generics like Integer, String, Character etc and we can't give primitives but this is a correct list/Collection initialization:

List<int[]> ls = new ArrayList<>();

An array of primitives can be defined as generic? Because as far as I know in Java <> are used to define generics. When I first saw that kind of initialization I was surprised and curious and didn't believe it.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Tarun Soni
  • 27
  • 4
  • 7
    An array of primitives is still an object... See also [Is an array a primitive type or an object (or something else entirely)?](https://stackoverflow.com/questions/12806739/is-an-array-a-primitive-type-or-an-object-or-something-else-entirely) and [Is an array an object in Java?](https://stackoverflow.com/questions/8781022/is-an-array-an-object-in-java) – Mark Rotteveel Dec 20 '22 at 15:37
  • 3
    Try `System.out.println(new int[0] instanceof Object);` - prints true, because all array types are `Object`s. – Andy Turner Dec 20 '22 at 15:40
  • 2
    "we are supposed to provide the generics like Integer, String, Character etc" you've got your terminology confused: you have to provide an _Object_ type like Integer, String etc. "Generics" just mean it applies to more than a single type. – Andy Turner Dec 20 '22 at 15:47

1 Answers1

7

While int is a primitive type, its array type int[] is a reference type. Instances of int[] are objects just as much as instances of String. Generics may take reference types as their type arguments, but not primitive types. So List<int> is not allowed, but List<int[]> is, because int[] is a reference type.

You probably got confused because you internalized a syntactic rule like "can't have lower-case identifiers inside the pointy brackets", which is a good approximation for the rule that "type arguments cannot be primitive types", but arrays of primitives are not primitives.

Brian Goetz
  • 90,105
  • 23
  • 150
  • 161