Foreword

In the previous section we explained StringBuilder VS StringBuffer and the difference between the two. In this section we will explain the wrapper class.

Packaging

We know that there are 8 basic data types in Java, divided into numeric types: byte, short, int, long, float, double. Character type: char. Boolean type: bool, so what is a wrapper class? Wrapper classes are object representations of 8 basic data types, and 8 types of wrapper classes are immutable and final (immutability cannot be destroyed by inheritance or extension) like string objects. We can know by looking at the packaging type Integer of int, as follows:

Java_entry_series_[4]_packaging_class_0.png

The following are the wrapper classes and constructor parameters corresponding to the basic data types:




Basic data typetype of packagingConstruction parameters

byte
Byte
byte or String


short
Short
short or String


int
Integer
int or String


long
Long
long or String


float
Float
float, double or String


double
Double
double or String


char
Character
char


boolean
Boolean
boolean or String


For example, when we instantiate the Integer wrapper class, since it is a wrapper for int, if we pass a number with decimal places, there is no doubt that the following exception is thrown:

 

 

public  class Main {

    public  static  void main (String [] args) {
        Integer a = new Integer ("12.5" );
    }
}

 

 

Java_entry_series_[4]_packaging_class_1.png

At the beginning, we directly threw out the concept of a wrapper class, but I don’t know if you have the same doubts as me, why do we use a wrapper class? For example, Integer is a wrapper for int. Can’t we just finish using int directly? How can we wrap it up? This requires us to understand what the packaging class does?

1. Wrapper class converts basic data types to objects (objects are needed when we need to pass parameters in a given method).

2. The package java.util only deals with object classes, so the wrapper class also has its place in this package.

3. The data structure only stores objects and basic data types.

4. In multithreading, we need objects to support thread synchronization.

In other words, existence is reasonable. It is wise to distinguish wrapper classes from basic data types in Java. When we program in an object-oriented way, we use wrapper classes. When it is easier to handle, we use basic Data type, everything depends on us.

Autoboxing and unboxing

Automatic boxing and unboxing were introduced in Java 5, which allows basic data types and wrapper classes to be easily converted between each other. Next, we implement boxing and unboxing through the conversion of basic data types and packaging classes. Boxing is the automatic conversion of basic data types into packaging classes, and vice versa.

 

 

        char ch = 'a' ;
        Character a = ch;

        ArrayList <Integer> arrayList = new ArrayList <Integer> ();
        arrayList.add ( 25 );
        System.out.println (arrayList.get ( 0));

 

 

As in the first one above, we converted the basic data type into an object, and we initialized the collection with the parameter type as a wrapper class (object), and then we added an int with a basic data type of 25 to this collection, and all of them were automatically boxed. In turn, we will unbox as follows:

 

 

        Character ch = 'a' ;
         char a = ch;
        ArrayList <Integer> arrayList = new ArrayList <Integer> ();
        arrayList.add ( 24 );
         int num = arrayList.get (0 );
        System.out.println (num);

 

 

In the above, we first convert the wrapper class to a basic data type, and then we add an int with a base data type of 24, which belongs to boxing, but at the end we assign a value to num of int when we get the data. Conversion of basic data types, that is, unboxing. At the same time we need to keep in mind that the wrapper class can be empty, and the basic data type cannot be empty. In other words, to make it nullable, we must use a wrapper class. This is not as advanced as C # syntax. If the basic data type is nullable, it can be defined in C # as follows:

int? a = null ;
Console.WriteLine (a == null);

Next, let’s look at the following question. May I ask: Is the following automatic boxing? If not, what does it show?

 

 

public  class Main {

    public  static  void main (String [] args) {

        char c = 'a' ;

        doSomething ( new Character (c));
    }

    static  void doSomething (Object obj) {

    }

}

 

 

We know that autoboxing is to convert the basic data type into a wrapper class. Above we defined a doSomething method with parameters of type Object. At the entry point of the program, we call this method and the parameters passed in are wrapper classes, so the above is not Autoboxing, it reflects the polymorphism through the wrapper class. So we need to keep in mind that autoboxing is the conversion of basic data types into wrapper classes, rather than one data type into other datatypes, which may be why autoboxing cannot convert String to a wrapper class.

Data type conversion

We still take the basic data type int as an example. There is an intValue method in the wrapper class Integer corresponding to int for unboxing. For example, if we want to convert a double to an int, the wrapper class implementation is as follows:

        double d = 135 .d;
        Double doubleWrapper = new Double (d);
        int integerValue = doubleWrapper.intValue ();
        System.out.println (integerValue);

We can also use the wrapper class type to convert to other basic data types through unboxing. This type of conversion will be used when we need to convert basic data types to objects and use them to get other basic data types. With the above conversion, we need to write a large piece of code. However, we can achieve the same purpose in the following simple ways:

        double d = 135 .d;
        int integerValue = (int ) d;
        System.out.println (integerValue);

Detailed use of valueOf and parseInt

So far I know there are two ways to convert String objects to int or Integer, let’s take a look together.

Integer.parseInt

This method is the first way to convert String to int. It is simple and flexible. Let’s look at an example:

int i = Integer.parseInt ("123" ); System.out.println ("i:" + i);

If the provided String is not the correct number, the Integer.parseInt () method will throw a NumberFormatException, the same applies to conversion of other data types (such as float and Double) to String in Java. The Java API provides static methods such as Float.parseFloat () and Double.parseDouble () to perform data type conversion.

Integer.valueOf

This valueOf method is available in eight wrapper classes. This is also a way to convert String to int. Let’s also look at an example:

int i = Integer.valueOf ("000000081" );
 System.out.println ("i:" + i);

It will ignore leading zeros and convert the string to int. If the provided String is not the correct number, a NumberFormatException will also be thrown. There was no autoboxing before Java 1.4, but autoboxing was introduced in Java 1.5 (Java 5+), so it is recommended to use Integer.valueOf (int) instead of new Integer (int), because Integer can now range from -128 to Integer objects are cached between 127, and the same complete Integer (0) object can be handed to us every time, instead of wasting object construction on a brand new identical Integer object.

Java_entry_series_[4]_packaging_class_2.png

Java_entry_series_[4]_packaging_class_3.png

Let’s look at two examples to verify the above source code viewpoint:

 

 

        Integer i1 = 260 ;
        Integer i2 = 260 ;
        if (i1 == i2) {
            System.out.println ("i1 and i2 is equal" );
        } else {
            System.out.println ("i1 and i2 is not equal" );
        }

 

 

Next we look at an example, as follows:

 

 

        Integer i1 = 100 ;
        Integer i2 = 100 ;
        if (i1 == i2) {
            System.out.println ("i1 and i2 is equal" );
        } else {
            System.out.println ("i1 and i2 is not equal" );
        }

 

 

We see “i1 and i2 are equal” because the int value between -128 and 127 is in the range that most JVMs want to cache, so the VM actually uses the same object instance for i1 and i2 (hence the same memory address ), So it prints equal. The Integer.valueOf method is also overloaded. Let’s look at an example:

        Integer I = Integer.valueOf ("100", 2 );
        System.out.println (I);
        Integer i = Integer.valueOf ("101", 4 );
        System.out.println (i);

The second parameter represents the base. For example, the above two represent 100 by binary and 101 by quaternary. The calculation method is as follows:

Binary representation of 100: (1 * 2 ^ 2) + (0 * 2 ^ 1) + (0 * 2 ^ 0) = 4 + 0 + 0 = 4 .

The quaternary representation 101: (1 * 4 ^ 2) + (0 * 4 ^ 1) + (1 * 4 ^ 0) = 16 + 0 + 1 = 17.

Summary

The valueOf and parseInt methods are both used to convert String to Integer in Java, but there are slight differences between them (after the introduction of autoboxing in Java 1.5), we know by looking at the source code of the valueOf () method and found that it is internal The parseInt () method is called to convert the String to an Integer, but it also maintains a pool of integers from -128 to 127. If the requested integer is in the pool, it returns an object from the pool. This also means using the valueOf () method to return The two integer objects can be the same through the equality operator, and this caching of immutable objects really helps reduce garbage and helps the garbage collector. Another difference between the parseInt () and valueOf () methods is the return type, valueOf () returns an Integer object, and the parseInt () method returns an int primitive data type. Whether you use parseInt or valueOf to convert a String to a basic data type Int and a wrapper class Integer, if we need a basic data type Int, you can use parseInt. Since immutable objects can be safely cached in the pool and reused, this reduces it. The load of the garbage collector, so if an Integer object is needed, it is better to use valueOf.

 

The “==” or equal operator in Java is a binary operator provided by the Java programming language. It is used to compare primitives and objects. When comparing basic data types such as boolean, int, and float, using “==” works fine. , But when comparing objects, it will be confused with the equals method in Java, “==” compares two objects based on a memory reference. So the “==” operator only returns true when two object references are compared to indicate the exact same object, otherwise “==” will return false. After the introduction of autoboxing and unboxing in Java 5, using “==” to compare wrapper objects may cause unexpected results due to version issues.

 

Java entry series [1] string creation method

Java entry series [2] string features

Java entry series [3] stringbuilder string buffer

Java entry series [4] packaging class

Java entry series [5] inheritance abstract classes interfaceson

Java entry series [6] Principles of dynamic array

Java entry series [7] collection arraylist

Java entry series [8] principles of doubley linked list alogrithm

Java entry series [9] linkedlist source code analysis

Java entry series [10] Hash algorithm principle

Java entry series [11] Hashtable source code analysis

Java entry series [12] Hashcode and equals

Java entry series [13] Principles of the read-black tree algorithmn method

Java entry series [14] Hashmap source code ananlysis

 

Orignal link:https://www.cnblogs.com/CreateMyself/p/11437026.html