Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the reasons for designing wrapper classes in Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the reasons for the design of packaging classes in Java". In daily operation, I believe that many people have doubts about the reasons why packaging classes are designed in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "what are the reasons for designing packaging classes in Java?" Next, please follow the editor to study!

The mental map of the full text is as follows:

1. Why do you need wrapper classes?

In Java, everything is an object, and all operations need to be described in the form of an object. But there are eight basic types in Java besides objects (reference types), which are not objects. So, in order to convert the base type to an object, the easiest way is to "save the base type as a property of a class", that is, to wrap the basic data type, which is the origin of the wrapper class.

In this way, let's first implement a simple wrapper class ourselves, taking the wrapper basic type int as an example:

/ / wrapper class MyInt public class MyInt {private int number; / / basic data type public Int (int number) {/ / constructor, pass the basic data type this.number = number;} public int intValue () {/ / get the data in the wrapper class return this.number;}}

Test the wrapper class:

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

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

The wrapper class corresponding to the basic type (located in the java.lang package) byteByteshortShortintIntegerlongLongfloatFloatdoubleDoublecharCharacterbooleanBoolean

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

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

Decorated by final, that is, Java's built-in "wrapper class cannot be inherited".

two。 Packing and unpacking

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

Boxing: converts a basic data type to a wrapper class (the constructor of each wrapper class can receive variables of its own data type)

Unpacking: extract the wrapped primitive type data from the wrapper class (using the xxxValue method of the wrapper class)

Taking Integer as an example, let's take a look at how Java's built-in wrapper classes are unboxed:

Integer obj = new Integer (10); / / automatic packing int temp = obj.intValue (); / / automatic unpacking

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

I don't know if you have noticed that value is declared as final, that is, "once a wrapper has been constructed, it is not allowed to change the value wrapped in it."

In addition, it should be noted that this form of code is "before JDK 1.5"! "after JDK 1.5", Java designers provide "automatic boxing" and "automatic unpacking" mechanisms to facilitate development, and can directly use the objects of the packaging class for mathematical calculation.

Taking Integer as an example, let's take a look at the process of automatic unpacking:

Integer obj = 10; / / automatic packing. Basic data type int-> wrapper class Integer int temp = obj; / / unpack automatically. Integer-> int obj + +; / / directly use the objects of the wrapper class for mathematical calculation System.out.println (temp * obj)

See, the conversion from the basic data type to the wrapper class does not need to use the constructor as above. Similarly, the conversion from the wrapper class to the basic data type does not require us to manually call the wrapper class's xxxValue method. That's why they call them automatic.

Let's take a look at the decompiled file of this code, what exactly is the underlying principle:

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

As you can see, the underlying principle of autoboxing is that the valueOf method of the wrapper class is called, while the underlying layer of the automatic unboxing calls the wrapper class's intValue () method.

3. Not simple Integer.valueOf

We have seen the source code of the intValue method for automatic unpacking, which is very simple. Let's take a look at valueOf for autoboxing. There is nothing to say about other wrapper classes, but there is something about this method in Integer:

What is IntegerCache? click in and have a look:

IntegerCache is a static inner class in the Integer class. Combining these two pieces of code, we can probably know that IntegerCache is actually a "cache" in which a buffer cache is defined to store data of type Integer. "the cache interval is [- 128,127]".

Go back to the source code of valueOf: it will first determine whether the argument I of type int is within the cacheable range, if so, get the corresponding Integer object directly from the cache IntegerCache; if not, it will new a new Integer object.

Combined with this feature, let's look at a topic, two similar code logic, 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}

We know that = = has two application scenarios:

For reference types, it is judged whether the memory address is equal or not

For basic types, the judgment is whether the values are equal or not.

Starting with A1, the Integer object is cached because its value is within the cache range of InterCache. When creating a2, because its value is equal to A1, the Integer object with the value of 127is directly taken out of the cache and used by a2, that is, the object references of A1 and a2 both point to the same address.

For b1 and b2, b1 and b2 point to different memory addresses because 128 is not within the cache range of IntegerCache, so they have to honestly open up their own space.

Obviously, the existence of the InterCache caching mechanism may confuse us when programming, so it is best to use the .equals method to compare whether the Integer values are equal. Integer overrides the .equals method:

Of course, other wrapper classes do not have a caching mechanism, but they also overload the .equals method, which is used to determine whether they are equal by value. Therefore, it is concluded that "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 unpacking mechanism, the basic data type can be automatically converted to a wrapper class, and Object is the parent of all classes, that is, "Object can accept all data types" (reference types, basic types)!

If you don't believe it, you can just use the Object class to receive a basic data type int.

Object obj = 10; int temp = (Integer) obj

Explain what happened to the above code. The following picture is very important. Take a closer look at it:

5. Widespread 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 basic types, only data of reference types. What if we want to store basic types of data like 1, 2, 3? For example, we can declare an array list of Integer objects as follows:

ArrayList list = new ArrayList ()

Add int data to this list:

List.add (3)

The above call will cause an automatic boxing operation at the bottom:

Int n = list.get (I)

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 collection based on a subscript I and receive it with the basic data type int:

Int n = list.get (I)

The above call will cause an automatic unpacking operation at the bottom:

Int n = list.get (I) .intValue ()

6. Data type conversion

In addition, in addition to its wide application in collections, the wrapper class includes an important function, which is to provide a way to change string data into a basic data type, illustrated by several representative classes:

Integer:

Double:

Boolean:

These methods are identified by static, that is, they are jointly maintained by all their corresponding objects, and the method is accessed directly through the class name. For example:

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

It is important to note that there is no method to convert a string into a character in the Character class, because there is already a charAt () method in the String class that fetches the character content according to the index.

At this point, the study of "what are the reasons for the design of packaging classes in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report