Basic type takes precedence over packing basic type

original
2012/12/13 21:12
Number of readings 435

Java 1.5 adds auto boxing and auto unboxing.

Difference between basic type and basic packing type:

1: Basic types have only values, while boxing types have different identities from their values

2: The basic type has only values, while the boxing type has a non functional value in addition to all the functional values of the corresponding basic type: null

3: The basic type usually saves more time and space than the boxing type

 Comparator<Integer> naturalOrder = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 < o2 ? -1 : (o1 == o2 ?  0 : 1); } }; System.out.println(naturalOrder.compare(new Integer(10), new Integer(10))); //The result is 1 Reason: The calculation of o1<o2 on the expression will cause the Integer instance to be unpacked automatically, and then the expression o1==o2 is executed. It performs identity comparison on two object references. If o1 and o2 refer to Integer instances that represent the same int value, the result returns false. It is almost always wrong to apply the==operator to the boxing type
 static Integer i; public static void main(String[] args) { if(i==42) System.out.println("Unbelievable"); } //Result java.lang.NullPointerException Reason: i is an Integer, not an int, and all initial values are null When basic types and packing types are mixed in one operation, the packing type will be unpacked automatically. If the null object reference is unpacked automatically, you will get a NullPointerException
 Long sum=0L; long startTime=new Date().getTime(); for(long i=0; i<Integer.MAX_VALUE;i++){ sum+=i; } long endTime=new Date().getTime(); System. out. println ("Total time:"+(endTime startTime)); //Total time: 29079 Change to long sum=0L; //Total time: 6724 Cause: Variables are repeatedly packed and unpacked, resulting in significant performance degradation
When to use the packing type:

1: As elements, keys, and values in a collection

2: In parameterized types, the boxed type must be used as a type parameter, because Java does not allow the use of basic types

3: When making reflected method calls, you must use the boxed primitive type

Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
zero Collection
zero fabulous
 Back to top
Top