String str1 = new String("str"); String str2 = new String("str"); System.out.println ( "== Comparison:" + (str1 == str2)); System.out.println("equal比较:"+ str1.equals(str2)); String str3 = "str1"; String str4 = "str1"; System.out.println ( "== Comparison:" + (Str3 == str4)); System.out.println("equal比较:"+ str3.equals(str4));
Output:
== Comparison: to false
equal comparison: true
== Comparison: to true
comparison equal: true
The results can be found, equals to instantiate objects by a new, or by automatic packing to instantiate objects, the result is true, and returns results when used autoboxing == true, the use of new time returns false. It can be found through the source code:
public boolean equals(Object obj) { return (this == obj); }
Here the definition of equals and == are equivalent, but the results Why is not the same cause?
The reason is that the String class equals rewritten to :
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } } return false; }
Here again need attention equals five points:
1 自反性:对任意引用值X,x.equals(x)的返回值一定为true.
2 对称性:对于任何引用值x,y,当且仅当y.equals(x)返回值为true时,x.equals(y)的返回值一定为true;
3 传递性:如果x.equals(y)=true, y.equals(z)=true,则x.equals(z)=true
4 一致性:如果参与比较的对象没任何改变,则对象比较的结果也不应该有任何改变
5 非空性:任何非空的引用值X,x.equals(null)的返回值一定为false
最后总结得出结论:
equal:是用来比较两个对象内部的内容是否相等的,由于所有的类都是继承自java.lang.Object类的,所以如果没有对该方法进行覆盖的话,调用
的仍然是Object类中的方法,而Object中的equal方法返回的却是==的判断,因此,如果在没有进行该方法的覆盖后,调用该方法是没有
任何意义的。在java面向对象的处理中我们一般在javabean中都要选择重写equals方法,使用hibernate后,我们要生成数据库的映射文件与实体类,这是我们就最好在实体类中进行equals方法的重写,重写时我们可以根据自己的定义来实现该方法只要遵守那五条原则,例如对于一个student类我们定义只要在学号相同时我们就认为这两个对象时相等的;同时我们还要重写hashcode方法。
==: is used to determine two object addresses are the same, i.e., whether or not refer to the same object . Compare a pointer operation in the true sense.