您的位置:首页 > 其它

==和equal()的区别

2015-09-16 00:00 211 查看
摘要: 有关于==和equal()的区别,==不多说比较的是基本类型的值和引用类型的地址值;很多人应该是困惑equal(),

有关于==和equal()的区别,==不多说比较的是基本类型的值和引用类型的地址值;很多人应该是困惑equal(),这个其实equal()是Object中的默认方法。String只是继承和重写了Object中equal()方法,说白了:在Object中比较的是两个对象的地址值,在String中比较的是两个的字符串的内容这个在API里都有体现。
以 T1

String s1 = new String("hello");
String s2 = new String("hello");

System.out.println(s1 == s2); //false

System.out.println(s1.equals(s2));//true

T2

String s3 = new String("hello");
String s4 = "hello";

System.out.println(s3 == s4);//false

System.out.println(s3.equals(s4));//true

T3

String s5 = "hello";
String s6 = "hello";

System.out.println(s5 == s6);//true

System.out.println(s5.equals(s6));//true

为了便于理解我用以T4作为注释
T4
String s = new String(“hello”);
String s = “hello”;的区别?
第一句话造了两个对象。(一个或者两个)
第二句话造了一个对象。(也可能没有)
然后这个也就有了一个关于拼接是否相等的问题
String s1 = "hello";

String s2 = "world";

String s3 = "helloworld";

System.out.println(s3 == s1 + s2);//false

System.out.println((s1+s2).equals(s3));//true

System.out.println("helloworld" == s1 + s2);//false

System.out.println("helloworld" == "hello" + "world"); // true

在这个里面有一个细节:字符串常量相加和变量相加的区别:

变量拼接,先开空间,然后拼接

常量拼接,先拼接,找,存在,就不开空间了,否则就开空间存储。

数组中的这个equals和==的问题

int arr1[]={1,2,3};

int arr2[]={1,2,3};

System.out.println(arr1.equals(arr2));//false这个并不是重写的方法

System.out.println(Arrays.equals(arr1,arr2));//true

System.out.println(arr1==arr2);//false

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  == equal()