0

Why List<int> list1 = new ArrayList<>(); doesn't working, and why List<int[]> list3 = new ArrayList<>(); and List<Integer[]> list4 = new ArrayList<>(); is working?

import java.util.ArrayList;
import java.util.List;

public class Test
{
    public static void main(String[] args)
    {
        List<int> list1 = new ArrayList<>(); // why is doesn't working
        List<Integer> list2 = new ArrayList<>();
        List<int[]> list3 = new ArrayList<>(); // why working
        List<Integer[]> list4 = new ArrayList<>(); // why working
    }
}
Denys_newbie
  • 1,140
  • 5
  • 15

2 Answers2

2

In java, you have primitive types and you have reference types.
int is a primitive type and Integer is a reference type.

In java generics you have type parameters. In other words, a type parameter is a place holder that can be replaced by the name of a reference type. A type parameter cannot be replaced with a primitive type. Hence List<int> is not allowed.

List<Integer> is allowed since Integer is a reference type.

In java, an array is also a reference type, even if it is an array of primitive types. Hence int[] is a reference type and therefore List<int[]> is allowed.

Abra
  • 19,142
  • 7
  • 29
  • 41
  • 2
    Primitive types are types, they don't exist outside the type system. What you call "types" should be called "reference types". – Joachim Sauer Aug 28 '20 at 11:24
  • @JoachimSauer look again, please. – Abra Aug 28 '20 at 11:28
  • ```List list1 = new ArrayList<>();``` I understand why it is not working if autoboxing doesnt't existed. But why ```int``` doesn't get converted into ```Integer```? – Denys_newbie Aug 28 '20 at 11:31
  • @Denis_newbie autoboxing does not apply to type parameters. By the way, the java API documentation uses the term **Type Parameters** Refer to, for example, the _javadoc_ for class [`java.util.List`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html) – Abra Aug 28 '20 at 11:38
2

In Java Generics, you never make a primitive type as a reference, like :

List<int> List<double> ArrayList<long> 

because those aren't objects !! int the java Generics, we code the generic classes with objects !!