Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ArrayList<Integer> optimized by the JDK to perform like int[]?

Tags:

java

We're taught that Java's ArrayList is less efficient for integers, because the list actually contains pointers, while an array of ints contains the integers in place, thus avoiding memory allocations and access.

My question is whether the JDK/JIT compiler optimizes this kind of inefficiency away? It has all the information to conclude these implementations are functionally equivalent , so it might as well replace ArrayList with an int[]-backed implementation under the hood.

like image 543
ripper234 Avatar asked Dec 31 '10 22:12

ripper234


People also ask

Can you use int in ArrayList Java?

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

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

An array can be converted to an ArrayList using the following methods: 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.

Which of the following options are properties of ArrayList in Java?

Java ArrayList class can contain duplicate elements. Java ArrayList class maintains insertion order. Java ArrayList class is non synchronized. Java ArrayList allows random access because the array works on an index basis.

How do you declare an integer in ArrayList?

ArrayList<Integer> numbers = new ArrayList<>(Arrays. asList(1, 2, 3, 4, 5, 6)); This is how you declare an ArrayList of Integer values. You can do the same to create an ArrayList with String objects as well, e.g.


1 Answers

No, it can't, because you can store null in an ArrayList.

EDIT: Oh, and it also can't because generics are erased at compile time — at run time, the JRE can't distinguish ArrayLists by their element types. IOW, it's worse than just null — you can store any object in an ArrayList<Integer>.

like image 195
Luke Maurer Avatar answered Sep 19 '22 23:09

Luke Maurer