1. equals()
Object类中的equals()方法用来判断两个对象是否相等;
示例1:
/* object类中的equals方法 public boolean equals(Object obj){ return (this == obj) } Object类中的equals方法判断两个类是否相等,使用“==”不能判断内容是否相等,只能判断两类的内存地址是否相等; 所有要重写Object类中的equals方法 */ public class EqualTest{ public static void main(String[] args){ int i = 100; int k = 100; System.out.println(i==k); MyTime m1 = new MyTime(2021,1,30); MyTime m2 = new MyTime(2021,1,30); System.out.println(m1.equals(m2)); MyTime m3 = null; System.out.println(m1.equals(m3)); } } class MyTime{ int year; int month; int day; public MyTime(){ } public MyTime(int year, int month, int day){ this.year = year; this.month = month; this.day = day; } /* public boolean equals(Object obj){ //重写父类Object中的equals方法,类名,参数,返回值必须相同; if(obj instanceof MyTime){ //要使用obj调用子类中的属性要向下转型 MyTime mt = (MyTime)obj; if(this.year == mt.year && this.month == mt.month && this.day == mt.day){ return true; } } return false; } */ //优化重写equals方法; public boolean equals(Object obj){ if(obj == null){ return false; } if(!(obj instanceof MyTime)){ return false; } if(this == obj){ return true; } MyTime mt = (MyTime)obj; return this.year == mt.year && this.month == mt.month && this.day == mt.day; } }
示例2:
/* equals()重写 */ public class EqualTest01{ public static void main(String[] args){ User u1 = new User("zhangsan", new Address("yantaqu", "12222")); User u2 = new User("zhangsan", new Address("yantaqu", "12222")); System.out.println(u1.equals(u2)); } } class Address{ String street; String zipcode; public Address(){ } public Address(String street, String zipcode){ this.street = street; this.zipcode = zipcode; } // public boolean equals(Object obj){ if(obj == null || !(obj instanceof Address)) return false; if(this == obj) return true; Address ad = (Address)obj; if(this.street.equals(ad.street) && this.zipcode.equals(ad.zipcode)){ return true; } return false; } } class User{ String name; Address address; public User(){ } public User(String name, Address address){ this.name = name; this.address = address; } public boolean equals(Object obj){ if(obj == null || !(obj instanceof User)) return false; if(this == obj) return true; User u = (User)obj; if(this.name.equals(u.name) && this.address.equals(u.address)){ return true; } return false; } }
2. toString()
object类中的toString(),返回类名的哈希值转换为十六进制;一般都会重写;
/* String类也重写了toString()和equals()方法 */ public class StringTest{ public static void main(String[] args){ String s1 = "test1"; String s2 = "test1"; System.out.println(s1 == s2); String s3 = new String("test3"); String s4 = new String("test3"); System.out.println(s3 == s4); //false System.out.println(s3.equals(s4)); //true 说明 String类已经重写了equals()方法; String s5 = new String("hello"); System.out.println(s5); //hello; System.out.println(s5.toString()); //hello 说明String类重写了toString()方法; } }
3. finalize()
当一个java对象即将被垃圾回收器回收的时候,垃圾回收器负责调用finalize()方法;自动调用finalize()方法,不用手动调用;
调用可能会有时机,会在垃圾对象比较多时候自用调用;也可使用system.gc()建议调用,使用system.gc()后调用可能性会更大;