三:equals方法
equals用来判断给定的对象是否与当前对象相等
public boolean equals(Object obj){
return(this == obj)
}
如果当前对象与obj相等则返回true
如果当前对象与obj不相等则返回false
equals方法可以被子类重写,从而改变具体算法
实体类:
package com.entity;
public class Employee {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
public Employee() {
}
@Override
public boolean equals(Object obj) {
Employee employee = (Employee) obj;
return this.getId().equals(employee.getId())?true:false;
}
}
测试类:
package com.test;
import com.entity.Employee;
public class Test3 {
public static void main(String[] args) {
Employee employee1 = new Employee("012345","喜羊羊");
Employee employee2 = new Employee("012345","懒羊羊");
boolean bool= employee1.equals(employee2);
System.out.println(bool?"两个对象id是相同的":"两个对象id是不相同的"); //两个对象id是相同的
}
}
四:getclass方法
getclass方法返回当前对象的运行时类(class)对象
public final native Class<?>getClass();
此方法是个终极本地方法,不允许子类进行重写
五.hashCode方法
hashCode方法返回该对象的int类型哈希值
public native int hashCode();
此方法为提高哈希表的性能而支持,通常在非特殊情况下不必要重写此方法
package com.test;
import com.entity.Users;
public class Test4 {
public static void main(String[] args) {
Users u0 = new Users("no8888","懒洋洋",8);
Users u1 = u0;
System.out.println(u0.equals(u1));//true
System.out.println(u0.hashCode());//23934342
System.out.println(u1.hashCode());//23934342
System.out.println(new Users().hashCode());//22307196
}
}
六.clone方法
clone方法返回当前对象的一个副本
protected native Object clone() throws CloneNotSupportedException;
被克隆的对象与当前对象不具有同一个引用,但是具有完全相同的对象属性,欲克隆当前对象则当前对象所属类应实现Cloneable接口
实体类:
package com.entity;
public class Employee implements Cloneable{
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
public Employee() {
}
@Override
public boolean equals(Object obj) {
Employee employee = (Employee) obj;
return this.getId().equals(employee.getId())?true:false;
}
@Override
public Employee clone() throws CloneNotSupportedException {
System.out.println("开始克隆对象");
return (Employee) super.clone();
}
}
测试类:
package com.test;
import com.entity.Employee;
import java.util.UUID;
public class Test5 {
public static void main(String[] args) {
Employee employee = new Employee(UUID.randomUUID().toString(),"喜羊羊");
try {
Employee cloneEmp = employee.clone();
System.out.println("当前对象与克隆对象是否相等"+(employee==cloneEmp));//当前对象与克隆对象是否相等false
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}