记得当初学java时,我预测考试会考equals 和 ==,没想预测成功了。然后,慢慢的,发现在用java语言的过程中,会经常用到,虽然用过了很多次,但有时还是会有点糊涂,加上前段时间一个同学笔试也问了这个,我就心想干脆总结一下:
首先搞清楚’equals‘方法是比较String对象的内容的,它不管你比较对象的地址,而’==‘是比较两者的值,比较的前提是双方式处于同一内存地址中,否者就算两者值是一样,比较的结果也是false
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
System.out.println(str1.equals(str3));
System.out.println(str1==str3);
System.out.println(str1==str2);
上面这段代码中,str1和str2声明后将保存在一个叫做常量池的地方(在堆中分配出来的一块存储区域,用于存储显式的String,float或者integer.例如String str="hello"; 这个字符串是显式声明,所以存储在常量池),而str3直接在堆中开辟了一块新的地址,所以两者的地址是不一样。由于equals方法是不管比较对象的地址的,==比较的前提是在同一内存地址中(或者理解成同一对象),因此显而易见,程序运行结果就是:
true
false
true
ps:当你声明了一个String对象 String str = new String(),如果要判断str是否为空,不能通过str==null来判断,要用 str.length()==0 或者 str.isEmpty() 来判断,因为当你实例化一个对象后就会在内存分配空间,这个对象是实实在在存在的,只是这个空间里没有东西而已(我曾经被这个给坑惨过)。
前段时间一个室友笔试碰到了一个问题:
- Integer a = 127;
- Integer b = 127;
- System.out.println(a == b);
- System.out.println(a.equals(b));
- a = 128;
- b = 128;
- System.out.println(a == b);
- System.out.println(a.equals(b));
上面这段程序的运行结果是:
true
true
false
true
为什么当a和b变成128时就不行了呢?
首先解读 Interger a = 127 这个声明相当于Interger.valueOf(127),查看valueOf的源代码:
/** * Returns a {@code Integer} instance for the specified integer value. * <p> * If it is not necessary to get a new {@code Integer} instance, it is * recommended to use this method instead of the constructor, since it * maintains a cache of instances which may result in better performance. * * @param i * the integer value to store in the instance. * @return a {@code Integer} instance containing {@code i}. * @since 1.5 */
public static Integer valueOf(int i) {
return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
}
可以看到,该方法的取值范围是-128-127,超出这个范围话取到的就不是同一对象了,这也就是为什么当a和b的值变成128时 a==b 就是false了。所以当比较整形值的时候,直接用int类型以避免这种情况的发生
希望这个对暂时有迷惑的同学能有所帮助,如果有说的不对的地方,欢迎指出纠正