- equals函数在什么地方
- 所有的类当中都会有equals函数
- equals函数的作用
- “==”操作符的作用:判断两个引用是否指向堆内存当中的同一块地址
publicclassTest{
publicstaticvoid main(String args []){
User u1 =newUser();
User u2 =newUser();
User u3 = u1;
boolean b1 = u1 == u2;
boolean b2 = u1 == u3;
System.out.println(b1);
System.out.println(b2);
}
}
结果:
D:\work\src>javac Test.java
D:\work\src>java Test
false
true
- equals函数的作用是用来比较,两个对象的内容是否相等(类型和值都相等)
- 复写equals函数的方法
classUser{
String name;
int age;
public boolean equals(Object obj){
if(this== obj){
returntrue;
}
//instanceof作用:判断前面的对象是不是后面对象的类型
boolean b = obj instanceof User;
if(b){
//obj向下转型为User对象
User u =(User)obj;
if(this.age == u.age &&this.name.equals(u.name)){
returntrue;
}
else{
returnfalse;
}
}
else{
returnfalse;
}
}
}
publicclassTest{
publicstaticvoid main(String args []){
User u1 =newUser();
User u2 =newUser();
User u3 =newUser();
u1.name ="zhagnsan";
u1.age =12;
u2.name ="lisi";
u2.age =12;
u3.name ="zhagnsan";
u3.age =12;
System.out.println(u1.equals(u2));
System.out.println(u1.equals(u3));
}
}
结果:
D:\work\src>javac User.java
D:\work\src>javac Test.java
D:\work\src>java Test
false
true
时间: 2024-11-05 08:05:52