🎓 Do your best and obey the destiny. The blogger is studying for a master’s degree in Southeast University. He loves fitness and basketball, and is willing to share what he sees and gains related to technology. He pays close attention to the public account @flying Veal, and gets the update of the article as soon as possible

🎁 This article has been included in the “CS-Wiki” Gitee official recommended project, has accumulated 1.5K + STAR, is committed to creating a perfect back-end knowledge system, in the road of technology to avoid detours, welcome friends to come to exchange and study

🍉 If you do not have a good project, you can refer to a project I wrote “Open source community system Echo” Gitee official recommended project, so far has accumulated 330+ star, SpringBoot + MyBatis + Redis + Kafka + Elasticsearch + Spring Security +… And provide detailed development documents and supporting tutorials. Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo


Recently, the update frequency of articles has been slow, because I was preparing for summer internship recently, and I was thinking of writing articles while reviewing, so that I could have the best of both sides. Later, I found that it would take four or five hours or even more to write an article that was more comfortable to read, but I could finish the review of this knowledge point in half an hour. The spring recruitment is coming and time is relatively urgent. Therefore, the article may be changed to one or two days a week recently. In addition, those who are preparing for summer internship like me can contact me to communicate with each other 😊

The mind map of the whole text is as follows:

1. Why is the wrapper class needed

In Java, everything is an object, and all operations are required to be described as objects. But there are eight basic types in Java besides objects (reference types) that are not objects. So, in order to convert a primitive type to an object, the simplest way to do that is to store the primitive type as a property of a class, that is, to wrap the primitive datatype, which is where the wrapper class comes in.

So, let’s implement a simple wrapper class ourselves, using the wrapper base int as an example:

// Wrap class MyInt
public class MyInt {
    private int number; // Basic data type
    
    public Int (int number){ // Constructor, passing in the basic data type
        this.number = number;
    }
    
    public int intValue(a){ // Get the data in the wrapper class
        return this.number; }}Copy the code

Test the wrapper class:

public static void main(String[] args) {
    MyInt temp = new Int(100); // 100 is the basic datatype, which is wrapped as an object
    int result = temp.intValue(); // Get the basic data type from the object
    System.out.println(result);
}
Copy the code

Of course, the wrapper class we implemented ourselves is very simple, and Java gives us a more complete built-in wrapper class:

Basic types of Corresponding wrapper class (in the java.lang package)
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

The first six classes derive from the common superclass Number, while Character and Boolean are direct subclasses of Object.

Take a look at the declaration of the wrapper class, using Integer as an example:

Final, which means that Java’s built-in wrapper classes cannot be inherited.

2. Packing and unpacking

OK, now that we know that there are basic data types and their corresponding wrapper classes, the conversions between them are called boxing and unboxing:

  • Boxing: Converts basic data types into wrapper classes (each wrapper class constructor can accept variables of its own data type)
  • Unpacking: Remove the wrapped primitive type data from the wrapper class (using the xxxValue method of the wrapper class)

Using Integer as an example, let’s look at how Java’s built-in wrapper classes are unboxed:

Integer obj = new Integer(10);  // Automatic boxing
int temp = obj.intValue();  	// Automatic unpacking
Copy the code

As you can see, the wrapper classes are used in much the same way as the ones we wrote above. In fact, the underlying implementation of the two methods in Integer is similar to the code we wrote above.

If you noticed, value is declared final, which means that once a wrapper is constructed, it is not allowed to change the value wrapped in it.

Also, note that this form of code is pre-JDK 1.5!! After JDK 1.5, Java designers provided automatic boxing and unboxing mechanisms for easy development, and can directly use the objects of the packaging class to perform mathematical calculations.

Using Integer as an example, let’s look at the automatic unboxing process:

Integer obj = 10;  	// Automatic boxing. Base data type int -> Wrapper class Integer
int temp = obj;  	// Automatic unpacking. Integer -> int
obj ++; // Use the wrapper class directly to do the math
System.out.println(temp * obj); 
Copy the code

See, the basic data type to wrapper class conversion, do not need to use the constructor as above, directly = done; Similarly, the wrapper class to the basic data type conversion, we do not need to manually call the wrapper class xxxValue method, directly = can be completed unboxing. That’s why they’re called automatic.

Let’s take a look at the decompiled file of this code and see what the underlying principle is:

Integer obj = Integer.valueOf(10);
int temp = obj.intValue();
Copy the code

As you can see, the underlying principle of autoboxing calls the valueOf method of the wrapper class, while the underlying principle of autounboxing calls the intValue() method of the wrapper class.

3. Integer.valueof is not simple

We have seen above the source code for the intValue method for automatic unboxing, very simple. Let’s look at valueOf for autoboxing. There’s not much to say about other wrapper classes, but there’s something interesting about this Integer method:

IntegerCache

IntegerCache is a static inner class of the Integer class. IntegerCache is a cache that defines a buffer cache for storing data of type Integer. The cache interval is [-128, 127].

ValueOf determines whether int I is in the cacheable range. If so, it fetches the corresponding Integer object directly from the cache. If it is not in the cache, a new Integer object is created.

Combined with this feature, let’s look at a problem where two types of code logic are similar, but get completely opposite results. :

public static void main(String args[]) {
    Integer a1 = 127;
    Integer a2 = 127;
    System.out.println(a1 == a2); // true

    Integer b1 = 128;
    Integer b2 = 128;
    System.out.println(b1 == b2); // false
}
Copy the code

As we know, == has two application scenarios:

  • For reference types, the determination is whether memory addresses are equal
  • For basic types, it’s whether the values are equal

Starting with a1, the Integer object is cached because its value is in InterCache. When a2 is created, its value is the same as a1, so the value of the Integer 127 is directly fetched from the cache for A2. In other words, both the object references of A1 and A2 are to the same address.

In the case of b1 and B2, 128 is not in the IntegerCache, so they have to create their own space, so b1 and B2 point to different memory addresses.

Obviously, InterCache can be confusing when programming, so it’s best to use.equals to compare Integer values for equality. Integer overrides the.equals method:

Of course, the other wrapper classes have no caching mechanism, but they also override.equals to determine equality based on values. Therefore, the conclusion is to use the equals method to compare the values of two wrapper class objects.

4. The Object class can accept all data types

To sum up, with the automatic unboxing mechanism, basic data types can be automatically converted to the wrapper class, and Object is the parent of all classes, that is, Object can accept all data types (reference type, basic type)!!

If you don’t believe me, you can use the Object class to receive a basic int.

Object obj = 10;
int temp = (Integer) obj;
Copy the code

To explain what’s happening in this code, it’s important to look closely at the following diagram:

5. Extensive use of wrapper classes in collections

In fact, the most common use of wrapper classes is in collections, because collections are not allowed to store data of primitive types, only reference types. What if we want to store basic types like 1, 2, and 3? For example, we can declare an arraylist of Integer objects as follows:

ArrayList<Integer> list = new ArrayList<>();
Copy the code

Add int to this list:

list.add(3); 
Copy the code

The above call will automatically box the container at the bottom:

list.add (Integer.valueOf(3));
Copy the code

The basic data type int is converted to an Integer object and stored in the collection.

Let’s get the corresponding Integer object from this set based on some subscript I and receive it with the basic data type int:

int n = list.get(i);
Copy the code

The above call will automatically unpack the box at the bottom:

int n = list.get(i).intValue();
Copy the code

6. Data type conversion

In addition to their widespread use in collections, wrapper classes also contain an important feature that provides methods for turning String data into primitive data types, illustrated by several representative classes:

Integer:

Double:

Boolean:

These methods are identified as static, that is, they are maintained by all objects that correspond to them, and the method is accessed directly by the class name. Here’s an example:

String str = "10";
int temp = Integer.parseInt(str);// String -> int
System.out.println(temp * 2); / / 20
Copy the code

Note that the Character class does not have a method that converts a String to a Character, because the String class already has a charAt() method that fetches the Character content based on the index.

| flying veal 🎉 pay close attention to the public, get updates immediately

  • The blogger is a master student in Southeast University. In her spare time, she runs a public account “Flying Veal”, which was opened on December 29, 2020/29. Focus on sharing computer basics (data structure + algorithm + computer network + database + operating system + Linux), Java basics and interview guide related original technical good articles. The purpose of this public account is to let you can quickly grasp the key knowledge, targeted. I hope you can support me and grow with veal 😃
  • And recommend personal maintenance of open source tutorial project: CS-Wiki (Gitee recommended project, has accumulated 1.5K + STAR), is committed to creating a perfect back-end knowledge system, in the road of technology to avoid detours, welcome friends to come to exchange learning ~ 😊
  • If you don’t have any outstanding projects, you can refer to the Gitee official recommended project of “Open Source Community System Echo” written by me, which has accumulated 330+ star so far. SpringBoot + MyBatis + Redis + Kafka + Elasticsearch + Spring Security +… And provide detailed development documents and supporting tutorials. Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo Echo