"=="与equals的区别与联系

  "=="可作用于基本类型变量和引用类型变量:

1.当作用于基本类型变量时,比较的是变量的值是否相等。

2.当作用于引用变量时,比较的是该变量在内存中地址。

  "equals"不能作用于基本类型变量,只能作用于引用类型变量

超类object()方法源码,equals() 方法是比较两个对象的内存地址是否相等:

1 public boolean equals(obj){
2     return (this==obj);
3 }

当有其他方法对equals()进行重写,那么比较的是所指向的对象的内容。

String类中equals源码:

 1  public boolean equals(Object anObject) {
 2         if (this == anObject) {
 3             return true;
 4         }
 5         if (anObject instanceof String) {
 6             String anotherString = (String)anObject;
 7             int n = count;
 8             if (n == anotherString.count) {
 9             char v1[] = value;
10             char v2[] = anotherString.value;
11             int i = offset;
12             int j = anotherString.offset;
13             while (n-- != 0) {
14                 if (v1[i++] != v2[j++])
15                 return false;
16             }
17             return true;
18             }
19         }
20         return false;
21         }

猜你喜欢

转载自www.cnblogs.com/ouhonglei/p/10931681.html
今日推荐