java 中的 .equals的问题
来源:百度知道 编辑:UC知道 时间:2024/06/04 03:18:28
String s1,s2;
s1=new String("we are students");
s2=new String("we are students");
System.out.println(s1.equals(s2)); //输出结果是:true。
System.out.println(s1==s2); //输出结果是:false
这是什么原因?
s1=new String("we are students");
s2=new String("we are students");
System.out.println(s1.equals(s2)); //输出结果是:true。
System.out.println(s1==s2); //输出结果是:false
这是什么原因?
.equals 比较的是两个字符串的内容
他们内容相同所以 true
s1==s2
比较的是两个字符串变量存储的地址
他们分别开辟了不同的内存,所以false
s1.equals(s2);
是表示两个字符串是否相等到
s1==s2;
是表示s1 和s2是否指向同一块内存地址
s1 s2只表示两个指向内存的引用
你new了两个字符串
所以是两个不同的地址
equals()是比较两个字符串内容是否相同,
而==是比较两个字符串是否为同一个对象.
刚开始学有点不好理解.
equals是单纯比较两个字符串相同索引处字符是否相同。==比较的是内存地址,也就是引用的是否是同一个对象。