原文:https://www.liaoxuefeng.com/article/1256136507802816

正确使用Map,只需要正确实现hashCode()equals()就行了吗?

恐怕还不行。

确切地说,如果使用的是HashMap,那么只需要正确实现hashCode()equals()就够了。

但是,如果换成TreeMap,正确实现hashCode()equals(),结果并不一定正确。

代码胜于雄辩。先看作为key的class定义:

class Student implements Comparable<Student> {
final String name;
final int score; public Student(String name, int score) {
this.name = name;
this.score = score;
} @Override
public int hashCode() {
return Objects.hash(name, score);
} @Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student o = (Student) obj;
return Objects.equals(this.name, o.name) && this.score == o.score;
}
return false;
} @Override
public int compareTo(Student o) {
return this.score < o.score ? -1 : 1;
}
}

先用HashMap测试:

Map<Student, Integer> map = new HashMap<>();
map.put(new Student("Michael", 99), 99);
map.put(new Student("Bob", 88), 88);
map.put(new Student("Alice", 77), 77);
System.out.println(map.get(new Student("Michael", 99)));
System.out.println(map.get(new Student("Bob", 88)));
System.out.println(map.get(new Student("Alice", 77)));

输出为998877,一切正常。

HashMap改为TreeMap再测试:

Map<Student, Integer> map = new TreeMap<>();

输出为nullnullnull

怎么肥四?

说好的接口不变,实现类随便换现在不管用了?难道是JDK的bug?

遇到这种诡异的问题,首先在心里默念三遍:

  • JDK没有bug。
  • JDK没有bug。
  • JDK没有bug。

然后开始从自己的代码找原因。

先打开JDK的TreeMap文档,注意到这句话:

This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method

意思是,Map接口定义了使用equals()判定key是否相等,但是SortedMap却使用compareTo()来判断key是否相等,而TreeMap是一种SortedMap

所以,问题出在compareTo()方法上:

@Override
public int compareTo(Student o) {
return this.score < o.score ? -1 : 1;
}

上面这个定义,用来排序是没问题的,但是,没法判断相等。TreeMap根据key.compareTo(anther)==0判断是否相等,而不是equals()

所以,解决问题的关键是正确实现compareTo(),该相等的时候,必须返回0

@Override
public int compareTo(Student o) {
int n = Integer.compare(this.score, o.score);
return n != 0 ? n : this.name.compareTo(o.name);
}

修正代码后,再次运行,一切正常。

Java Map的正确使用方式的更多相关文章

  1. Java ThreadPool的正确打开方式花钱的年华 | 江南白衣(5星推荐)

    线程池应对于突然增大.来不及处理的请求,无非两种应对方式: 将未完成的请求放在队列里等待 临时增加处理线程,等高峰回落后再结束临时线程 JDK的Executors.newFixedPool() 和ne ...

  2. map的正确删除方式

    遍历删除map元素的正确方式是 for(itor = maptemplate.begin; itor != maptemplate.end(); ) {      if(neederase)     ...

  3. Java map双括号初始化方式的问题

    关于Java双括号的初始化凡是确实很方便,特别是在常量文件中,无可替代.如下所示: Map map = new HashMap() { { put("Name", "Un ...

  4. Java流的正确关闭方式

    因为流是无论如何一定要关闭的,所以要写在finally里.如下: BufferedReader reader = null; try { reader = (BufferedReader) getRe ...

  5. Java遍历Map的3种方式

    package test; import java.util.Collection; import java.util.HashMap; import java.util.Map; import ja ...

  6. Redis实现分布式锁的正确使用方式(java版本)

    Redis实现分布式锁的正确使用方式(java版本) 本文使用第三方开源组件Jedis实现Redis客户端,且只考虑Redis服务端单机部署的场景. 分布式锁一般有三种实现方式: 1. 数据库乐观锁: ...

  7. java 遍历Map的四种方式

      java 遍历Map的四种方式 CreationTime--2018年7月16日16点15分 Author:Marydon 一.迭代key&value 第一种方式:迭代entrySet 1 ...

  8. java map遍历方式及效率

    本文转载自Java Map遍历方式的选择. 只给出遍历方式及结论.测试数据可以去原文看. 如果你使用HashMap 同时遍历key和value时,keySet与entrySet方法的性能差异取决于ke ...

  9. Java Collection - 遍历map的几种方式

    作者:zhaoguhong(赵孤鸿) 出处:http://www.cnblogs.com/zhaoguhong/ 本文版权归作者和博客园共有,转载请注明出处 ---------------- 总结 如 ...

随机推荐

  1. LeetCode_405. Convert a Number to Hexadecimal

    405. Convert a Number to Hexadecimal Easy Given an integer, write an algorithm to convert it to hexa ...

  2. [LeetCode] 202. Happy Number 快乐数

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

  3. Kubernetes StatefulSet

    StatefulSet 简介 在Kubernetes中,Pod的管理对象RC.Deployment.DaemonSet和Job都是面向无状态的服务.但现实中有很多服务是有状态的,特别是一些复杂的中间件 ...

  4. 【视频开发】【CUDA开发】FFMPEG硬件加速-nvidia方案

    1.目标 <1>显卡性能参数: <2>方案可行性: 2.平台信息 2.1.查看当前显卡信息 命令:  lspci |grep VGA  信息:  01:00.0 VGA com ...

  5. nodepad++格式化html代码

    如果没有安装插件

  6. linux环境变量 bash_profile

    linux环境变量 bash_profile [root@iZ23uewresmZ ~]# vi /root/.bash_profile <pre># .bash_profile # Ge ...

  7. QT_QML 界面设计Row和Column布局

    Column与Row的使用方式类似,下面以Column为例子: Column{ x: label_poseParamValue.x + label_poseParamValue.width + 10 ...

  8. LeetCode 43. 字符串相乘(Multiply Strings)

    43. 字符串相乘 43. Multiply Strings 题目描述 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式. ...

  9. 04 Mybatis 框架的环境搭建及入门案例

    1.搭建 Mybatis 开发环境 mybatis的环境搭建 第一步:创建maven工程并导入坐标 第二步:创建实体类和dao的接口 第三步:创建Mybatis的主配置文件 SqlMapConifg. ...

  10. Python 爬取陈都灵百度图片

    Python 爬取陈都灵百度图片 标签(空格分隔): 随笔 今天意外发现了自己以前写的一篇爬虫脚本,爬取的是我的女神陈都灵,尝试运行了一下发现居然还能用.故把脚本贴出来分享一下. import req ...