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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
| /**
* 判断两个对象是否相等。 这个函数用处是:
* <ul>
* <li>可以容忍 null
* </li><li>可以容忍不同类型的 Number
* </li><li>对数组,集合, Map 会深层比较
* </li></ul>
* 当然,如果你重写的 equals 方法会优先
*
* @param a1
* 比较对象1
* @param a2
* 比较对象2
* @return 是否相等
*/
public static boolean equals(Object a1, Object a2) {
if (a1 == a2)
return true;
if (a1 == null || a2 == null)
return false;
if (a1.equals(a2))
return true;
if (a1 instanceof Number)
return a2 instanceof Number && a1.toString().equals(a2.toString());
if (a1 instanceof Map && a2 instanceof Map) {
Map< ?, ?> m1 = (Map< ?, ?>) a1;
Map< ?, ?> m2 = (Map< ?, ?>) a2;
if (m1.size() != m2.size())
return false;
for (Entry< ?, ?> e : m1.entrySet()) {
Object key = e.getKey();
if (!m2.containsKey(key) || !equals(m1.get(key), m2.get(key)))
return false;
}
return true;
} else if (a1.getClass().isArray()) {
if (a2.getClass().isArray()) {
int len = Array.getLength(a1);
if (len != Array.getLength(a2))
return false;
for (int i = 0; i < len; i++) {
if (!equals(Array.get(a1, i), Array.get(a2, i)))
return false;
}
return true;
} else if (a2 instanceof List) {
return equals(a1, Lang.collection2array((List<Object>) a2,
Object.class));
}
return false;
} else if (a1 instanceof List) {
if (a2 instanceof List) {
List< ?> l1 = (List< ?>) a1;
List< ?> l2 = (List< ?>) a2;
if (l1.size() != l2.size())
return false;
int i = 0;
for (Iterator< ?> it = l1.iterator(); it.hasNext();) {
if (!equals(it.next(), l2.get(i++)))
return false;
}
return true;
} else if (a2.getClass().isArray()) {
return equals(Lang.collection2array((List< object>) a1,
Object.class), a2);
}
return false;
} else if (a1 instanceof Collection && a2 instanceof Collection) {
Collection< ?> c1 = (Collection< ?>) a1;
Collection< ?> c2 = (Collection< ?>) a2;
if (c1.size() != c2.size())
return false;
return c1.containsAll(c2) && c2.containsAll(c1);
}
return false;
} |
Recent Comments