The function of the so-called packaging class is to convert the original data type into a reference data type. The following article mainly introduces to you the solutions to the problems encountered when comparing Java packaging classes. Detailed examples are given in the article. Friends who need it can refer to the code. Let’s take a look together.
Preface
This article mainly introduces solutions to some problems encountered when comparing Java packaging classes, and shares them for future reference. Please refer to it for reference and study. I won’t say much more below. Let’s take a look at the detailed introduction.
Example 1:
##
Integer a = 1; Integer b = 2; Integer c = 3; Integer d = 3; Integer e= 321; Integer f= 321; Long g = 3L; System.out.println(c == d); //1 System.out.println(e == f); //2 System.out.println(c == (a+b)); //3 System.out.println(c.equals(a+b));//4 System.out.println(g == (a+b)); //5 System.out.println(g.equals(a+b)); //6Output result
true false true true true false1. Packaging class comparison will not automatically unpack, but there will be a cache in Integer to store numbers from -128 to 127, so the address values of c and d are the same.
Long.equals(Object object) determines that the type does not match and returns false.
Example 2:
##
Long a = 1L; Integer b = 1; System.out.println(a.equals(1)); //7 System.out.println(a.equals(1L)); System.out.println(a.equals(b));
false true false
7.
, int 1 is packed into Integer, which is naturally a different type from Long.
public boolean equals(Object obj) { if (obj instanceof Long) { return value == ((Long)obj).longValue(); } return false; }
Summary:
When using automatic unpacking/packing, packaging Comparison between classes does not automatically unpack, it is an address comparison, and there is caching that will affect the results.
When comparing using the equals method of the wrapper class, since the wrapper class does not automatically convert the type, when the types are different, even if the values are the same, false will be returned. Therefore, when comparing values with wrapper classes, do not use '=='. When using the equals method, pay attention to the same type, or directly use the basic data type for comparison.
The above is the detailed content of Solving problems encountered when comparing Java package classes. For more information, please follow other related articles on the PHP Chinese website!