If I would use int for a specific variable, but would have to deal with some kind of collection with it, which means the int will get converted into wrapped int/int object and vice versa many times, it makes sense that in this case, it would be performance-wise and semantically better to always use the Integer for this variable, so to avoid constant casting between int and Integer (i.e. when you would add the int to collection, it would have to be casted to Integer (actually it would have to be newly created), and when you would get it from the collection, it would have to be casted to int)?
-
2Is this a question? Aside from the question mark at the end? It appears like a statement – Danielson Jul 21 '15 at 08:35
-
If it is a question, a small hint: There are many libraries offering primitive collections for Java. – Marco13 Jul 21 '15 at 08:41
2 Answers
To be consistent, there are two possibilities here:
either you use wrapper classes all the time
or you use primitive collections (e. g. Commons Primitives)
But if you don't have a very special case here and you tracked some performance issues down to that casting, the performance impact of casting is probably negligible here. You should not worry about such micro optimizations if you don't really need to.
Using the Wrapper classes would not always bring a benefit, too. Think about the following code:
List<Integer> numbers, squares;
//initialize both, fill numbers
for(Integer number: numbers)
squares.add(number*number);
for(int i: numbers) {
squares.add(i*i);
}
In the first loop, you get your number straigt from the collection without casting, but then it is casted to an int, multiplied with itself, and autoboxed back to an Integer before storing it in squares.
In the second loop, you convert your Integer to an int when fetching it from the list, multiply it with itself, and the autobox it back to an Integer before storing it.
In both cases, you have autoboxing involved. To fully avoid this, you had to use primitive collections, or int[].

- 1,175
- 1
- 8
- 25
If you are worrying about the efficiency of autoboxing/autounboxing, you can manually convert the primitive type to its wrapper class object. E.g.
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<5;i++)
{
list.add(Integer.valueOf(i));
}
According to the API of Integer.valueOf(),this method is likely to yield significantly better space and time performance by caching frequently requested values.

- 1,582
- 11
- 12