浏览代码

因为Map/Set的key存储的是不重复的对象,依据hashCode和equals进行判断,所以Set存储的对象需要重写这两个方法

liuhuan 6 年之前
父节点
当前提交
3b72e1704f

+ 19 - 0
hutool-core/src/main/java/cn/hutool/core/lang/Pair.java

@@ -1,6 +1,7 @@
 package cn.hutool.core.lang;
 
 import java.io.Serializable;
+import java.util.Objects;
 
 import cn.hutool.core.clone.CloneSupport;
 
@@ -50,4 +51,22 @@ public class Pair<K, V> extends CloneSupport<Pair<K, V>> implements Serializable
 	public String toString() {
 		return "Pair [key=" + key + ", value=" + value + "]";
 	}
+
+	@Override
+	public boolean equals(Object o) {
+		if (this == o)
+			return true;
+		if (o instanceof Pair) {
+			Pair<?, ?> pair = (Pair<?, ?>) o;
+			return Objects.equals(getKey(), pair.getKey()) &&
+					Objects.equals(getValue(), pair.getValue());
+		}
+		return false;
+	}
+
+	@Override
+	public int hashCode() {
+		//copy from 1.8 HashMap.Node
+		return Objects.hashCode(key) ^ Objects.hashCode(value);
+	}
 }

+ 17 - 6
hutool-core/src/main/java/cn/hutool/core/map/TableMap.java

@@ -1,12 +1,7 @@
 package cn.hutool.core.map;
 
 import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
 
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.util.ArrayUtil;
@@ -154,6 +149,22 @@ public class TableMap<K, V> implements Map<K, V>, Serializable {
 		public V setValue(V value) {
 			throw new UnsupportedOperationException("setValue not supported.");
 		}
+		@Override
+		public final boolean equals(Object o) {
+			if (o == this)
+				return true;
+			if (o instanceof Map.Entry) {
+				Map.Entry<?,?> e = (Map.Entry<?,?>)o;
+				return Objects.equals(key, e.getKey()) &&
+						Objects.equals(value, e.getValue());
+			}
+			return false;
+		}
 
+		@Override
+		public int hashCode() {
+			//copy from 1.8 HashMap.Node
+			return Objects.hashCode(key) ^ Objects.hashCode(value);
+		}
 	}
 }