Packaging (Wrapper Class)
Wrapper classes are wrappers for native data types.
Because there are 8 native data types, there should be 8 wrapper classes.
All packaging Classes (8) are located under Java.lang.
The 8 wrapper classes in Java are: Byte, short, Integer, Long, Float, Double, Character, Boolean, they are used the same way, Bidirectional conversions of native data types to wrapper types can be implemented.
The following is an example of the main integer class.
Integer
The integer class wraps the value of the int type into an object.
Integer constructs an object of the corresponding integer number by constructing the following method:
public Integer (int value);
The public int intvalue () method returns the integer value that is wrapped by the wrapper class.
Automatic packing/unpacking (autoboxing/unboxing)
A new feature of JDK5.0 is automatic boxing and automatic unpacking.
Automatic boxing/unpacking greatly facilitates the use of basic types of data and their wrapper classes.
Auto-boxing : Basic types are automatically converted to wrapper classes (int >> Integer)
Automatic unpacking : Wrapper classes are automatically converted to basic types (Integer >> int)
For example, the following:
Import java.util.ArrayList; Import java.util.Collection; Classvoidnew arraylist<integer>(); C.add (3); // }}
Cache
The following procedure is very strange:
Class boxtest2{ void main (string[] args) {Integer i1 =n; Integer i2 =if (i1 = = i2) {System.out.println ("I1 = = i2"else {System.out.println ("I1! = i2" ); } }}
When the two numbers are 100, the = = judgment is equal, and when the two numbers are 200, the judgments are unequal.
Looking at the internal implementation code, the integerclass has a cache that caches integers between -128~127 .
When valueof is called, no new objects are generated, but objects are fetched from the cache. This can improve performance.
A new object is bound to be generated when using the construction method.
Java wrapper class Auto boxing and unpacking