public class Student {
 private String name;
 private int age;
 public Student(String name,int age)
 {
 this.name=name;
 this.age=age;
 }
 public static void main(String[] args)
 {
 Student st1 = new Student("zhang",20);
 Student st2 = new Student("zhang",20);
 if(st1.equals(st2))
 System.out.print("xiangdeng");
 else
 System.out.print("buxiangdeng");
 
 
 }
}
为什么输出buxiangdeng?stringclass

解决方案 »

  1.   

    equals也比较内存地址吗? 不是就==比较吗
      

  2.   

    你直接调用了Object的equals方法,而Object的equals方法就是==方法 比较的是内存地址,String类能用equals比较内容而不是比较内存地址是因为String类自己重写了equals方法,所以你想要比较你这个Student 类的大小那么你这个Student 类也需要重写Object的equals方法
      

  3.   

    new 出来的东西都是新开辟一块空间的,equal比的是内存地址,所以不相等
      

  4.   

    good  new出来的东西是新开辟一块内存的  new出来的对象要注意跟传递引用赋值是不一样的
      

  5.   

    st1和st2是两个不同的对象,当然不相等了
    比较的是hashcode
    hashcode又跟对象的内存地址有关
    不同的对象,内存地址肯定不同,所以hashcode不同
    所以不是同一个除非你重写hashcode和equal方法
      

  6.   


    equals比较的是对象
    ==比较的是对象中的值