Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting intValue from Integer, does it make any sense?

Tags:

java

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?

like image 263
James Raitsev Avatar asked Feb 17 '12 15:02

James Raitsev


People also ask

What is the point of the intValue () in Java?

intValue. Returns the value of this Integer as an int . Returns: the numeric value represented by this object after conversion to type int .

What does intValue do?

intValue. Returns the value of the specified number as an int , which may involve rounding or truncation. Returns: the numeric value represented by this object after conversion to type int .

Can you increment an integer?

Integer objects are immutable, so you cannot modify the value once they have been created.

Does integer take the same amount of space as int?

As already mentioned int is a primitive data type and takes 32 bits(4 bytes) to store. On other hand Integer is an object which takes 128 bits (16 bytes) to store its int value.


2 Answers

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.

like image 200
Jesper Avatar answered Oct 05 '22 03:10

Jesper


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 : )

like image 34
Alex Avatar answered Oct 05 '22 03:10

Alex