I've been using int in for-loop. Like below:

for (int i = 0; i < 100 ; i++) {
     //Do something...
}

If I use Integer instead of int, like below, does it makes any difference?

for (Integer i = 0; i < 100 ; i++) {
     //Do something...
}
有帮助吗?

解决方案

Yes, it will require auto-unboxing and auto-boxing for each iteration. It'll work the same way, and you don't need to do anything to make it work, but it's unnecessary and easily avoided.

Also it might slightly slow down the loop for no real advantage.

Basically Integer should only ever be used when you actually need the number to be an Object (for example when you put it into a collection, when null is a valid value, ...). At all other times, you should use the primitive types where possible (int, char, ...).

其他提示

I always choose primitive over Wrappers, When ever I can.

Your code works fine.

But, though very minor difference,

While run time, If we use Wrappers Boxing conversions and Unboxing Conversions happens at Runtime,Obviously that takes more time.

If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p

And vice-versa, this time will be saved in case,if we use Primitives.

I assume you already know the difference between int and Integer.
The loops will behave the same, but using int is preferable when you don't need Integer. Don't do that, it waste time (Capitalizing the "i" and adding "eger" :)). Furthermore, it's not efficient since auto-unboxing/auto-boxing will be done on each iteration.

Use int when you can live without Integer.

Using Integer will incur a performance cost due to boxing, so use int.

However, if you intend to use i within the loop body as, say a hash map key, then use the reference type Integer.

The only big thing(though I wouldn't do it myself & won't advise you to do that either) I could think about using in such a scenario is

for (Integer i = 0; i < 100 ; i++) {
     i = null; // Can do this here but not in the other loop
     // Obviously this is not going to be the only line here, unless you wanna get a NPE
     // Just something, which you COULD DO
}

Other than this, I really doubt if its going to matter much. Though using int is preferred. Also, boxing and auto-boxing for every iteration, is not a good thing(when you can just use int directly).

Thanks to Autoboxing and Unboxing a feature of Java 5, It does not.

No it does not make any difference in functioning. Auto boxing and and auto-unboxing feature helps you with i++ in the loop

No it won't. Integer is a wrapper which adds some functionality to the primitive int type. If you are not going to use that functionality, its better to stick to int.

In this case it might not make a lot of difference but suppose you were to use say Integer[] instead of int[], then youd be wasting a LOT of memory and speed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top