Java操作符==的理解及正确使用
结论
如果"==“用于比较基本数据类型(Java中有8种:byte, short, int, long, float, double, char, boolean),则比较的是它们的值是否相等。
如果”=="用于比较类对象,则比较的是它们的引用是否相同。
实验
int和Integer
// int and Integer
int a = 1000;
int b = 1000;
Integer c = Integer.valueOf(1000);
Integer d = Integer.valueOf(1000);
System.out.println(a==b); // true. compare values.
System.out.println(c==d); // false. compare references.
System.out.println(a==c); // true. Integer automatically unpacks boxes into an int type.
注意int与Integer比较时,Integer先自动卸箱,再比较。
String
// String comparison
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println(s1 == s2); // true. compare references. Their references are equal.
System.out.println(s1 == s3); // false.
System.out.println(s3 == s4); // false.
// view memory addresses
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s2));
System.out.println(System.identityHashCode(s3));
System.out.println(System.identityHashCode(s4));
注意String是final类,对象创建后不可改变。对于上述代码中的s1和s2,这种初始化方式涉及到字符串常量共享机制,即如果堆中已经存在,则不再创建新的对象,所以s1和s2指向同一个对象(可以查看s1和s2的内存地址,二者是一样的)。但是对于使用new创建的String类对象,系统总是会创建新的对象,所以s3和s4指向不同的对象。
null
// null
Object o1 = new Object();
o1 = null;
System.out.println(null==null); // true.
System.out.println(o1==null); // true.
==也可以用于判断对象是否是null。
扩展
很多情况下,我们需要判断对象的内容是否相同,而不是判断对象的引用是否相同。这时我们需要用到Object类中的方法equals()。
// normal situations
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // true
由于Object是所有类的父类,所以每个类继承了equals()方法,我们在自定义的类中可以重写该方法,来实现我们想要的结果。String类也重写了该方法,使得两个字符串的内容相同时返回真,否则为假。
如果上述代码中的s1为null,则程序会抛出NullPointerException,因此调用对象的equals()之前需要判断是否为null。那么如果我们希望equals()判断的范围包括null,则可以使用Objects(注意不是Object)中的equals()方法。
// null. When we are not sure whether the object is null, we should use Objects.equals(a,b).
String s3 = null;
String s4 = null;
// System.out.println(s3.equals(s4)); // NullPointerException
System.out.println(Objects.equals(s3, s4)); // true.
但是Objects的equals()方法,有个注意事项,即如果是对两个不同类型的对象进行比较,则总是返回假。
// Note that, if the class types of two class objects are different, Objects.equals(a,b) returns false always.
Integer a = Integer.valueOf(1);
long b = 1L;
System.out.println(Objects.equals(a, b)); // false. Although their values are equal.
以上就是这片博客的全部内容,后面还会增加更多Java语言相关的学习心得和总结。