-2

So I understand that you have to make a "new" object when adding an object to an arraylist:

ex: ArrayList<CookieOrder> orders = new ArrayList<CookieOrder>(); orders.add(new CookieOrder("cookie", 5)); 

but do you have to do this when the arraylist consists of only one data type

ex: ArrayList<int> numbers = new ArrayList<int>(); numbers.add(new int(2)); or numbers.add(2); 
2
  • You can't use keyword new with primitives, you just declare them and assign a value, you use new with objects. And you cant have an ArrayList of type int. Commented Dec 4, 2017 at 0:16
  • You do use the keyword 'new' with arrays of primitives. Commented Dec 4, 2017 at 0:22

1 Answer 1

1

There is no need to initialize a new "integer" object, because the integer already exists. You can add to an integer arraylist by doing just array.add(2);

Also, ArrayLists in java do not allow primitive types such as ints and doubles as storage. You have to use the classes of them, For example

List<Integer> numbers = new ArrayList<Integer>(); 

For more information, see this post. Why I can't have int in the type of ArrayList?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.