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
比较的是hashcode
hashcode又跟对象的内存地址有关
不同的对象,内存地址肯定不同,所以hashcode不同
所以不是同一个除非你重写hashcode和equal方法
equals比较的是对象
==比较的是对象中的值