package com.zq0804;
import java.util.Objects;
public class Test extends Object {
int id;
String name;
int age;
int phonenum;
// Integer i;
int[] array;
Test test;
public Test(int id, String name, int age, int phonenum){
this.id = id;
this.name = name;
this.age = age;
this.phonenum = phonenum;
}
public boolean equals(Test anObject){
if(this == anObject){ //先比较两个对象的地址,肯定不同
return true;
}
if(anObject==null || anObject.getClass() != this.getClass()){ //int无父类类型对象
return false;
}
if(anObject.name instanceof String){ //instanceof判断类型,如果类型一致,强制转型
String anotherString = (String) anObject.name;
//比较长度
int n = this.name.length();
if(n==anotherString.length()){
for(int i=0; i<n; i++){
if(anotherString.charAt(i) != this.name.charAt(i)){
return false;
}
}
return true && id == anObject.id && age == anObject.age && phonenum == anObject.phonenum;
}
}
return false;
}
// public boolean equals(int o) { //比较数值,字符
// if(this == o){
// return true;
// }
// if(o==null ){ //int无父类类型对象
// return false;
// }
//
// return Objects.equals(o, this.id);
// }
//
// public boolean equals(String o){
// if(this == o){
// return true;
// }
// if(o==null || o.getClass() != this.getClass()){ //int无父类类型对象
// return false;
// }
// if(o instanceof String){ //instanceof判断类型,如果类型一致,强制转型
// String anotherString = (String) o;
// //比较长度
// int n = this.name.length();
// if(n==anotherString.length()){
// for(int i=0; i<n; i++){
// if(anotherString.charAt(i) != this.name.charAt(i)){
// return false;
// }
// }
// return true;
// }
// }
// return false;
// }
//
public static void main(String[] args){
String B = "abc"; //new直接创建新地址
String C = "abc";
int a = 10; //int 无法New 在常量池
int b = 5;
Test A = new Test(0001, "zq", 24, 1885504496); //Test类创建A对象
Test anObject = new Test(0001, new String("zq"), 24, 1885504496); //同一类构造函数创建对象地址相同
// System.out.println(A.name==anObject.name); //A调用equals函数,Test类中this指代A, 地址一样直接比较字符串了
System.out.println(A.equals(anObject));
// A.equals(B, C);
// A.equals(a, b);
// new Test(0001, "zq", 23, "18056634029");
}
public void equals(int a, int b){
if(a==b){
System.out.println("Equals(int a, int b)+true");
}
else
System.out.println("Equals(int a, int b)+false");
}
public void equals(String A, String B){
if (A==B){ //比较对象的引用地址==,或int值(无法改地址)
System.out.println("Equals(String A, String B)+true");
}
else
System.out.println("Equals(String A, String B)+false");
}
}
在这里插入代码片
Equals 方法重写
最新推荐文章于 2022-05-08 19:42:31 发布