使用EqualsBuilder和HashCodeBuilder重写equals、hashCode方法

--
package com.osc.demo;

import java.util.List;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class Teacher {
	private String name;
	private int age;
	private List<Student> student;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public List<Student> getStudent() {
		return student;
	}

	public void setStudent(List<Student> student) {
		this.student = student;
	}

	@Override
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj);
	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}
}
--
package com.osc.demo;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class Student {
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj);
	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}
}
--
package com.osc.demo;

import java.util.ArrayList;
import java.util.List;

public class Test {
	public static void main(String[] args) {
		Student studentOne = new Student();
		studentOne.setName("张柏芝");
		studentOne.setAge(34);
		List<Student> listOne = new ArrayList<Student>();
		listOne.add(studentOne);
		Teacher teacherOne = new Teacher();
		teacherOne.setName("陈冠希");
		teacherOne.setAge(33);
		teacherOne.setStudent(listOne);

		Student studentTwo = new Student();
		studentTwo.setName("张柏芝");
		studentTwo.setAge(34);
		List<Student> listTwo = new ArrayList<Student>();
		listTwo.add(studentTwo);
		Teacher teacherTwo = new Teacher();
		teacherTwo.setName("陈冠希");
		teacherTwo.setAge(33);
		teacherTwo.setStudent(listTwo);

		System.out.println(teacherOne == teacherTwo);
		System.out.println(teacherOne.equals(teacherTwo));
	}
}

--

false
true

你可能感兴趣的:(使用EqualsBuilder和HashCodeBuilder重写equals、hashCode方法)