本帖最后由 吴超 于 2012-6-26 20:24 编辑
根据这些特性,我们可以写出如下代码:
1 public class Customer implements Serializable {
2 private static final long serialVersionUID = 1L;
3
4 private String id;
5 private String name;
6 private String role;
7
8 @Override
9 public boolean equals(Object obj) {
10 if(obj == null) {
11 return false;
12 }
13
14 if(this == obj) {
15 return true;
16 }
17
18 if(!(obj instanceof Customer)) {
19 return false;
20 }
21
22 Customer other = (Customer)obj;
23 return (ObjectUtils.equals(id, other.id) &&
24 ObjectUtils.equals(name, other.name) &&
25 ObjectUtils.equals(role, other.role));
26 }
27
28 public String getId() {
29 return id;
30 }
31 public void setId(String id) {
32 this.id = id;
33 }
34 public String getName() {
35 return name;
36 }
37 public void setName(String name) {
38 this.name = name;
39 }
40 public String getRole() {
41 return role;
42 }
43 public void setRole(String role) {
44 this.role = role;
45 }
46 }
其中ObjectUtils类的代码如下:
1 public class ObjectUtils {
2
3 /**
4 * Compare whether the left and right is equals
5 * It has already considered the null case
6 *
7 * @param left
8 * @param right
9 * @return
10 */
11 public static boolean equals(Object left, Object right) {
12 if(left == null && right == null) {
13 return true;
14 }
15 if(left == null && right != null) {
16 return false;
17 }
18 return left.equals(right);
19 }
20 }
|