== 比较两个变量或者实例是不是指向同一个内存空间
equals()比较两个变量或者实例指向的内存空间的值是否相同
通过Object源码,我对==和equals的认识如下:
1.没有重写equals方法,比较的是两个引用是否指向同一内存空间
2.重写equals方法,如String类,重写Object类的equals方法,比较的是对象的内容是否相同
/**
* Indicates whether some other object is "equal to" this one.
* <p>
* The {@code equals} method implements an equivalence relation
* on non-null object references: 在非null对象上实现等价关系
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
* 自反性: 对于任何非空值 {@code x.equals(x)} 返回true
*
* <li>It is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
* 对称性:对于任何非空参考值 {@code x.equals(y)}返回true,{@code y.equals(x)}返回true
*
* <li>It is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
* 传递性:对于任何非空参考值 {@code x.equals(y)}返回true,{@code y.equals(z)}返回true,{@code x.equals(z)}返回true
*
* <li>It is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
* 一致性:对于任何非空参考值 {@code x.equals(y)} 多次调用返回值应该一致,都返回true或者false
*
* <li>For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
* 对于非空引用x:对于任何非空参考值 {@code x.equals(null)}返回false
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*
* == 和 equals的区别?
* 1.没有重写equasl方法,比较的是两个应用是否指向同一内存地址
* 3.重写equasl方法,如String类,比较的是对象的内容是否相同
*/
public boolean equals(Object obj) {
return (this == obj);
}
在上面源码中已经备注了,在重写equals方法的时候,应该遵循如下原则;
1.自反性:
2.对称性:
3.传递性:
4.一致性:
5.对于非空引用: