使用EqualsBuilder和HashCodeBuilder重写equals、hashCode方法
发表于8个月前(2014-08-31 22:49) 阅读(181) | 评论(0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
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
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
return
student;
}
public
void
setStudent(List
this .student = student;
}
@Override
public
boolean
equals(Object obj) {
return
EqualsBuilder.reflectionEquals( this , obj);
}
@Override
public
int
hashCode() {
return
HashCodeBuilder.reflectionHashCode( this );
}
}
|
--
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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 );
}
}
|
--
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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 new
ArrayList
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 new
ArrayList
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