2015-09-07 11:44:36 -06:00
|
|
|
// operators/Equivalence.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
public class Equivalence {
|
2021-02-04 07:21:51 -07:00
|
|
|
static void show(String desc, Integer n1, Integer n2) {
|
|
|
|
System.out.println(desc + ":");
|
|
|
|
System.out.printf(
|
|
|
|
"%d==%d %b %b%n", n1, n2, n1 == n2, n1.equals(n2));
|
|
|
|
}
|
|
|
|
@SuppressWarnings("deprecation")
|
|
|
|
public static void test(int value) {
|
|
|
|
Integer i1 = value; // [1]
|
|
|
|
Integer i2 = value;
|
|
|
|
show("Automatic", i1, i2);
|
2021-09-20 17:33:35 -06:00
|
|
|
// Old way, deprecated since Java 9:
|
2021-02-04 07:21:51 -07:00
|
|
|
Integer r1 = new Integer(value); // [2]
|
|
|
|
Integer r2 = new Integer(value);
|
|
|
|
show("new Integer()", r1, r2);
|
2021-09-20 17:33:35 -06:00
|
|
|
// Preferred since Java 9:
|
2021-02-04 07:21:51 -07:00
|
|
|
Integer v1 = Integer.valueOf(value); // [3]
|
|
|
|
Integer v2 = Integer.valueOf(value);
|
|
|
|
show("Integer.valueOf()", v1, v2);
|
|
|
|
// Primitives can't use equals():
|
|
|
|
int x = value; // [4]
|
|
|
|
int y = value;
|
|
|
|
// x.equals(y); // Doesn't compile
|
|
|
|
System.out.println("Primitive int:");
|
|
|
|
System.out.printf("%d==%d %b%n", x, y, x == y);
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
public static void main(String[] args) {
|
2021-02-04 07:21:51 -07:00
|
|
|
test(127);
|
|
|
|
test(128);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2021-02-04 07:21:51 -07:00
|
|
|
Automatic:
|
|
|
|
127==127 true true
|
|
|
|
new Integer():
|
|
|
|
127==127 false true
|
|
|
|
Integer.valueOf():
|
|
|
|
127==127 true true
|
|
|
|
Primitive int:
|
|
|
|
127==127 true
|
|
|
|
Automatic:
|
|
|
|
128==128 false true
|
|
|
|
new Integer():
|
|
|
|
128==128 false true
|
|
|
|
Integer.valueOf():
|
|
|
|
128==128 false true
|
|
|
|
Primitive int:
|
|
|
|
128==128 true
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|