Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to declare an ArrayList of type int.

Why does the following give me an error:

ArrayList<int> list1 = new ArrayList<int>(); 

But the following works:

ArrayList<Integer> list1 = new ArrayList<Integer>(); 

?

like image 769
programmingIsFun Avatar asked Jan 15 '13 23:01

programmingIsFun


People also ask

Can you use int in ArrayList?

ArrayList can not be used for primitive types, like int, char, etc.

How do you get an int from an ArrayList?

The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list.

How do you add an int ArrayList to an array in Java?

Using ArrayList. add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.

Can ArrayList have different data types?

It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types. We will discuss how we can use the Object class to create an ArrayList.


1 Answers

ArrayList can only reference types, not primitives. Integer is a class, not a primitive.

When you declare ArrayList<Integer> list1 = new ArrayList<Integer>(), you're creating an ArrayList which will store the Integer type, not the int primitive.

If you want to read about the difference between primitive and reference types, check out http://pages.cs.wisc.edu/~hasti/cs302/examples/primitiveVsRef.html

like image 56
Zach Latta Avatar answered Oct 11 '22 14:10

Zach Latta