In a certain project, the equivalence comparison between the wrapper class and the primitive type was wrong, so I wrote an article for newcomers.
DemoApp.java
public class DemoApp {
public static void main(String[] args) {
Integer x = 999999;
Integer y = 999999;
int z = 999999;
//Of the wrapper class==Comparison
if (x == y) {
System.out.println("same");
} else {
System.out.println("other");
}
//Comparison of wrapper classes by equals method
if (x.equals(y)) {
System.out.println("same");
} else {
System.out.println("other");
}
//Wrapper classes and primitive types==Comparison
if (x == z) {
System.out.println("same");
} else {
System.out.println("other");
}
//Comparison of wrapper class and primitive type equals method
if (x.equals(z)) {
System.out.println("same");
} else {
System.out.println("other");
}
}
}
Execution result
other
same
same
same
This is the result of defining a wrapper class with the same number and a variable of primitive type and comparing the values.
| Item number | conditions | result |
|---|---|---|
| 1 | Wrapper class and wrapper class==Equivalence comparison |
different |
| 2 | Wrapper class and wrapper classequalsEquivalence comparison by method |
the same |
| 3 | Wrapper class and primitive type==Equivalence comparison |
the same |
| 4 | Wrapper class and primitive typeequalsEquivalence comparison by method |
the same |
== determines whether it points to the same instance (object), but it is interesting that the wrapper class and primitive type are also determined to be ** the same **.
Recommended Posts