== 运算符:
-
若符号两边是基本数据类型,则会比较左右两端值是否相等。
int a = 10; int b = 10; if (a == b){ System.out.println("a == b"); } char aa = 'a'; char bb = 'a'; if (aa == bb){ System.out.println("aa == bb"); } String str1 = "hello"; String str2 = "hello"; if (str1 == str2){ System.out.println("str1 == str2"); }
-
若符号两边为引用数据类型(包括基本数据类型的包装类型)时,则会比较左右两端对象引用地址是否相同。
equals():// 当没有重写equals方法时,会比较二者的引用地址是都相同,结果不会输出 => newStr1 == newStr2 String newStr1 = new String("hello"); String newStr2 = new String("hello"); if (newStr1 == newStr2){ System.out.println("newStr1 == newStr2"); } // 若按照下面方式重写equals方法时,则会输出,将引用地址的比较转化为属性值得比较 @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Student)) return false; Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); }
equals():
-
在没有重写equals()方法时,默认比较两个对象的引用地址是否相同,若重写过equals方法,则会按照equalse方法中重写的规则进行比较
// 默认规则 public boolean equals(Object obj) { return (this == obj); }