Java中比较对象

基本类型

基本对象比较值.
当基本类型与对应的包装类比较时,值相等就相等.因为包装类会拆箱为基本类型.

引用类型

==和equals()比较的是两个对象引用是否相等.
如果需要通过两个对象的属性是否相等,需要重写Object的equals()方法.

字符串比较

因为字符串池(string pool)的存在,字符串的比较有很大不同.

通过==比较

看两段代码

public class Main {

   public static void main(String[] args) {

       String s1 = "CodeGym is the best website for learning Java!";
       String s2 = new String("CodeGym is the best website for learning Java!");
       System.out.println(s1 == s2);
   }
}

返回 false

public class Main {

   public static void main(String[] args) {

       String s1 = "CodeGym is the best website for learning Java!";
       String s2 = "CodeGym is the best website for learning Java!";
       System.out.println(s1 == s2);
   }
}

返回 true
每当我们通过String str = "...................."创建字符串时,程序会检查string pool是否存在相同的字符串.如果存在,则不会创建新字符串,并将str的引用指向string pool中相同字符串的地址.
现在来看第2段代码:

String s1 = "CodeGym is the best website for learning Java!";
String s2 = "CodeGym is the best website for learning Java!";

s2指向的地址和s1相同.s1在string pool中创建一个新字符串.s2引用指向s1在string pool的地址.
那么第一段代码没什么方法false呢?因为通过new关键字创建的字符串是存储在内存堆中.

通过equals()比较

在String类中重写了Object的equals()

public boolean equals(Object anObject) {
  if (this == anObject) {
    return true;
  } 
  if (anObject instanceof String) {
    String anotherString = (String)anObject;
    int n = value.length;
    if (n == anotherString.value.length) {
      char v1[] = value;
      char v2[] = anotherString.value;
      int i = 0;
      while (n-- != 0) {
        if (v1[i] != v2[i])
          return false;
        i++;
      }
      return true;
    }
  }
  return false;
}

可以看到在String.equals()方法中是比较字符串中每个字符.

记住要使用equals()来比较字符串.

原文地址:https://www.cnblogs.com/huangj/p/14306033.html