equals与“==”操纵符的较量
当前位置:以往代写 > JAVA 教程 >equals与“==”操纵符的较量
2019-06-14

equals与“==”操纵符的较量

equals与“==”操纵符的较量

副标题#e#

equals要领是Object类的一个要领,所有担任自Object类的类城市集成此要领,而且可以重载这个要领来实现各自的较量操纵,并且jdk也正是推荐这种做法。所以开拓人员尽可以在本身的类中实现本身的equals要领来完本钱身特定的较量成果,所以各个类的equals要领与= =之间并没有绝对的干系,这要按照各自类中本身的实现环境来看。也就是说大概会有两种环境产生:equals要领和= =沟通可能不沟通。在大都环境下这两者的区别就是毕竟是对工具的引用举办较量照旧对工具的值举办较量(其他非凡环境此处不予思量)。那么= =操纵符是较量的什么呢?= =操纵符是较量的工具的引用而不是工具的值。而且由下面的源代码可以看出在最初的Object工具中的equals要领是与= =操纵符完乐成能是沟通的。

源码:

java.lang.Object.equals()要领:

————————————————————-

public boolean equalss(Object obj) {
return (this = = obj);
}

————————————————————-

jdk文档中给出如下表明:

————————————————————-

The equalss method implements an equivalence relation:

? It is reflexive: for any reference value x, x.equalss(x) should return true.

? It is symmetric: for any reference values x and y, x.equalss(y) should return true if and only if y.equalss(x) returns true.

? It is transitive: for any reference values x, y, and z, if x.equalss(y) returns true and y.equalss(z) returns true, then x.equalss(z) should return true.

? It is consistent: for any reference values x and y, multiple invocations of x.equalss(y) consistently return true or consistently return false, provided no information used in equalss comparisons on the object is modified.

? For any non-null reference value x, x.equalss(null) should return false.

The equalss method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equals objects must have equals hash codes.

————————————————————-


#p#副标题#e#

由以上的注释可知equals要领和 = =操纵符是完成了沟通的较量成果,都是对工具的引用举办了较量。那么我们熟悉的String类的equals要领是对什么内容举办较量的呢?下面我们来看它的代码和注释:

源代码:

————————————————————-

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;
}

————————————————————-

此要领的注释为:

————————————————————-

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

————————————————————-

由上面的代码和注释可以获得String类的equal要领是对工具的值举办较量。

按照以上的接头可以得出结论:equal要领和= =操纵符是否存在区别要个体看待,要按照equal的每个实现环境来详细判定。

*******************************

    关键字:

在线提交作业