0

I have a quick question that I am a little unclear which is the better practice.

Say I have a collection, c, that holds the numbers 3, 5, and 8.

Collection<Integer> c = new ArrayList<Integer>(); c.add(3); c.add(5); c.add(8);

I understand the idea of a for-each loop, however I am unclear on one part.

Do I write: for(Integer i: c){} or for(int i: c)?

If possible, please comment on speed, efficacy, advantages, and disadvantages or each.

Will Pike
  • 281
  • 4
  • 17
  • The second can throw a NPE is your collection contains an element that is `null`. – Alexis C. Feb 21 '14 at 22:15
  • possible duplicate of [Why are there wrapper classes in Java?](http://stackoverflow.com/questions/3579035/why-are-there-wrapper-classes-in-java) – femtoRgon Feb 21 '14 at 22:15

3 Answers3

2

It depends on what you're doing inside the for-each loop, and whether you'll need to "re-box" an int, or how often you'll need to unbox an Integer. It also depends how or if you want null to be handled -- if you want null to be allowed, you have to use Integer.

Frankly, it's unlikely to make a significant difference either way.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

Integer maps an int value as object so an it can be null but an int can't. So an int is a basic type so it uses less memory than the Integer object

Athanor
  • 855
  • 1
  • 16
  • 34
1

Your collection contains Integers, this it's better to iterate using for (Integer i: c). You'll want to do this to avoid unnecessary unboxing of Integer to int.

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257