== 的作用
对于基本类型来说,它就是比较两个变量的值是否相等;对于引用类型来说,它其实是在比较两个引用变量是否引用的是同一块堆内存空间,或者说是否指向同一块堆内存空间
int a = 5;
int b = 5;
System.out.println(a==b); //true
String str1 = new String("abc");
String str2 = new String("abc");
String str3 = str1;
System.out.println(str1==str2); //false str1和str2分别指向不同的堆内存空间
System.out.println(str1==str3); //true 它们都是指向同一个的堆内存空间
equals 的作用
成员函数equals要稍微复杂一些,由于不同类中的equals的定义可能不同,所以其含义也可能不同。对于字符串类型,equals方法用来比较两个字符串的内容是否相等
String str1 = new String("abc");
String str2 = new String("abc");
String str3 = str1;
System.out.println(str1.equals(str2)); //true
System.out.println(str1.equals(str3)); //true
注意: 如果一个自定义的类中没有显式地定义equals方法,那么equals方法的作用与比较运算符 “ == ” 是一样的,都是用来比较两个变量是否指向同一个对象。
public class test{
test(){}
public static void main(String[] args){
test a = new test();
test b = new test();
test c = a;
System.out.println(a.equals(b)); //false
System.out.println(a.equals(c)); //true
}
}