public class Example8_1{
public static void main(String args[]){
String s1,s2;
s1=new String("天道酬勤");
s2=new String("天道酬勤");
System.out.println(s1.equals(s2)); //ture
System.out.println(s1==s2); // false
String s3,s4;
s3="勇者无敌";
s4="勇者无敌";
System.out.println(s3.equals(s4)); //ture
System.out.println(s3==s4); //ture
}
}
为什么第二个是false啊
== 是比较的两个String 的hashcode s1 和 s2 是new 出来的 两个内存地址不一样的字符串 hashcode也不一样 所以返回false s3和s4是在常量池里内存地址是一样的
s1和s2放在堆里了,有两份内存。"勇者无敌"放在方法区中,在内存中就一份。
new出来的s1和s2所分配的栈地址是不同的,所以是false
http://blog.csdn.net/fanfan4569/article/details/51579604
明白了,感谢各位的回答
说得简单点,这两个new出来的对象并不是同一个对象。
举个例子,
Ball ball1 = new FootBall();
Ball ball2 = new BasketBall();
这两个球,一个是足球,一个篮球,他们是不是一样的呢?