当前位置: 代码迷 >> 综合 >> 关于 TreeMap 和 HashMap 的去重操作
  详细解决方案

关于 TreeMap 和 HashMap 的去重操作

热度:5   发布时间:2023-12-27 16:56:53.0

HashMap

HashMap中对于 Key 的去重是根据hashCode 和 equals 实现的

示例代码

/*** @author wu*/
public class Main {public static void main(String[] args) {Map<Example, String> map = new HashMap<>();Example test1 = new Example(1, "wu");Example test2 = new Example(1, "wu");map.put(test1, "haha");map.put(test2, "hehe");// 如果类 Example 不重写 hashCode 和 equals 方法, map.size() == 2// 如果类 Example 重写 hashCode 和 equals 方法, map.size() == 1System.out.println(map.size());}
}class Example {private int id;private String name;public Example() {}public Example(int id, String name) {this.id = id;this.name = name;}@Overridepublic int hashCode() {return id + name.hashCode();}@Overridepublic boolean equals(Object other) {if(this == other) {return true;}if(!(other instanceof Example )) {return false;}Example temp = (Example ) other;if(temp.id == id && temp.name.equals(name)) {return true;}return false;}
}

TreeMap 依靠的是 Comparable 或 Comparator 来实现 Key 的去重

示例代码

/*** @author wu*/
public class Main {public static void main(String[] args) {Map<Example, String> map = new TreeMap<>();Example test1 = new Example(1, "wu");Example test2 = new Example(1, "wu");map.put(test1, "haha");map.put(test2, "hehe");//  通过实现了Comparable 的 toCompare 方法来去重// 如果 id 和 name 均相等,则 map.size() == 1, 否则 map.size() == 2System.out.println(map.size());}
}class Example implements Comparable<Example>{private int id;private String name;public Example() {}public Example(int id, String name) {this.id = id;this.name = name;}@Overridepublic int compareTo(Example o) {if(o.id == id && o.name.equals(name)) {return 0;}// 这里表示 this 对象如果和 o 不相等,则 Key  设置为小于输入的 oreturn -1;}
}

PS: 参考 Java 开发手册

  相关解决方案