问题
Why to use primitive types in java instead of Wrapper classes? I want to know that already we have wrapper classes in java, then why we need to use primitive types? What are the importance of primitive types in java?
回答1:
Your question is backwards. The primitive types are more fundamental than their wrappers.
Really the only useful thing that wrappers give you is the ability to be treated as a subclass of Object (so that they can be put into collections and so on). All the really useful stuff (like arithmetic and ordering) is provided by the primitive type.
Note that while you can say stuff like:
Integer i = Integer.valueOf(4);
Integer j = Integer.valueOf(2);
Integer k = i + j;
this is just a convenience. Underneath, the last line becomes something like:
Integer k = Integer.valueOf(i.intValue() + j.intValue());
so that the arithmetic occurs on the primitive values. (This convenience is known as boxing/unboxing.) There is a performance penalty to this, so that on my machine, this loop:
for (int i=0; i<10000000; i++) { }
is about 10 times faster than this loop:
for (Integer i=0; i<10000000; i++) { }
回答2:
In Java, every object has some space overhead. It depends on the JVM, and the size of a "word" on the target architecture (64-bit versus 32-bit), but I usually estimate that every object has about 40 bytes of "overhead" beyond what is needed for its fields.
So, for example, an array of 1024 bytes is one object, with 40 bytes of overhead; it has a length
member (an int
) which needs 4 bytes, and it needs 1 byte for each element, for a total of around 1k.
An array of 1024 Byte
instances has the overhead of the array itself, its length
member, and then about 41 bytes for every Byte
instance (40 bytes of overhead, plus 1 byte for data). Altogether, that's over 41k! Much more than a primitive byte[]
.
Since the wrapper types are immutable, there have been suggestions for clever tricks to make primitive data look like wrapped object instances, but so far, none of these mechanisms have been implemented.
回答3:
performance, primitive classes map to the processor without having to go through as many operations.
In the case of boolean, int and float - you can make them volatile and ensure that they do not require synchronization (Reads and writes are atomic)
回答4:
[humor] To save typing! This:
int i = 4;
int j = 38;
int k = i + j;
is shorter to type than:
Integer i = new Integer(4);
Integer j = new Integer(38);
Integer k = i + j;
[/humor]
In reality, the other answers say it better than I could.
来源:https://stackoverflow.com/questions/3257967/primitives-types-in-java