Which one is best in programming - int
or Integer
? Especially whenever both are doing the same task?
I am writing an application in Java. In most of the places of primitive data types, I use int
; and for objects, I use Integer
. So I am confused- which one is the best in places, where we have to use objects.
According to performance, which one is best for a Java application?
Use int
when possible, and use Integer
when needed. Since int
is a primitive, it will be faster. Modern JVMs know how to optimize Integer
s using auto-boxing, but if you're writing performance critical code, int
is the way to go.
Take a look at this and this article. Although you shouldn't treat them as absolute truths, they do show that objects will be slower than their primitive counterparts.
So, use int
whenever possible (I will repeat myself: if you're writing performance critical code). If a method requires an Integer, use that instead.
If you don't care about performance and want to do everything in an object oriented fashion, use Integer
.
Use int
wherever possible. Use Integer
only if:
Integer
can be null
, an int
always has an int value. List
(though you can use int
externally and have autoboxing hide the fact that the collection internally stores Integer
instances). Integer
or Object
, or doesn't work with primitive types. int
a primitive, typically it should be faster. It just carries the raw number data.
Integer
is an object, it carries some extra stuff so you eg can put the number in lists.
int is primitive, Integer is an int wrapped up as an object.
It really depends how you are going to be using them.
As an alternative view.... perhaps you should use neither Integer nor int.
If the value is really an object with behaviour - like say an amount of money, or a distance or something, then perhaps you should be using an object with behaviour.
You can see more about this kind of thing here:
http://www.time4tea.net/wiki/display/MAIN/Microtypes
Although this may be "slower", the additional type safety will make the programming, testing and debugging of your system much easier & faster.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.