Reputation: 96581
I am looking through the code someone wrote a while back and wondering whether I am missing something here
Assuming
List<Integer> runUids = new ArrayList<Integer>();
and later on as part of a loop
int runUID = runUidsAL.get(i).intValue();
Is there any reason why intValue()
needs to be called here?. Don't think it's needed here. Do you?
Upvotes: 6
Views: 23133
Reputation: 480
A real situation that I have lived a few minutes ago:
I have a list of Integer objects. Each Integer is the index of an other list whose positions I want to remove.
Then... I was doing that:
for (Integer index : positionsToRemoveList) {
historyRecord.remove(index);
}
Java was calling to the next method
public boolean remove(Object object);
Instead of:
public E remove(int location);
My "historyRecord" List wasn't being updated beacuse Java was trying to remove by an Object instead of by position.
The right way is:
for (Integer index : positionsToRemoveList) {
historyRecord.remove(index.intValue());
}
And this is my real story : )
Upvotes: 3
Reputation: 1890
It's there because Integer extends Number.
Number n = new Integer(5);
int i = n.intValue();
That second line may need an int value from n, and may not know if n was instantiated with an Integer or Double.
Upvotes: 2
Reputation: 4614
Integer is an object, while int is a primitive.
intValue() method converts between the Integer class to its primitive representation.
http://mindprod.com/jgloss/intvsinteger.html
Upvotes: 1
Reputation: 18379
Java 1.5 and above supports automatic boxing and unboxing, which mans you can assign an Integer
to an int
without using .intValue()
.
Upvotes: 1
Reputation: 207016
You didn't say so, but I assume that runUID
is an int
.
It's not necessary to call intValue()
explicitly on the Integer
object returned by runUidsAL.get(i)
; Java will do this automatically by auto-unboxing.
Upvotes: 11
Reputation: 2534
You can assign an int to a long, but not an Integer object, for example. On the other hand, the intValue() could give a NullPointerException if the Integer object is null.
Upvotes: 0