Why can't I have 'int' as the type of an ArrayList?

前端 未结 7 733
时光取名叫无心
时光取名叫无心 2020-12-05 06:17

I want to declare an ArrayList of type int.

Why does the following give me an error:

ArrayList list1 = new Array         


        
7条回答
  •  半阙折子戏
    2020-12-05 07:14

    The short answer is that generics (like ArrayList) do not accept primitive types (int), only objects (Integer).

    This is because classes like ArrayList are implemented as using Objects. Since every class inherits from Object, the compiler can just plug in other classes. But primitive types (like int) do not inherit from Object, for they are not classes. So, Sun/Oracle made the Integer class to help with this.

    So, in short: int is not an Object.

提交回复
热议问题