Solve problems encountered in Java wrapper class comparison

preface

This article mainly introduces the solutions to some problems encountered in the comparison of Java packaging classes, and shares them for your reference and learning. I won't say much below. Let's take a look at the detailed introduction together.

Example 1:

Output results

1. Compared with packing classes, the package will not be unpacked automatically, but there will be a cache in integer to store the number of - 128 to 127, so the address values of C and D are the same.

2. Address value comparison, cache is not used

3. When '= =', automatic unpacking occurs on the right, so the int value is actually being compared

4. When a + B is unpacked into int, the equals method of integer is passed in for automatic packaging. Within the equals method are value comparisons.

5. Can unpack into basic data type comparison

6. Equals of packaging class will judge the type, long In equals (object object), it is judged that the type does not match, and false is returned.

Example 2:

output

Looking at the package source code, you will find that you will first judge whether the types are the same.

7.a. When equals (1), int 1 is packaged as integer, which is naturally different from long.

Summary:

When automatic unpacking / packaging is used, the comparison between packaging classes will not unpack automatically. It is an address comparison, and there is a cache, which will affect the results.

When comparing with the equals method of the wrapper class, because the wrapper class does not automatically convert types, false will be returned even if the values are the same when the types are different. Therefore, when comparing values with wrapper classes, do not use '= =', pay attention to the same type when using equals method, or directly compare with the basic data type.

Well, the above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>