Java中Map的使用

来源:互联网 发布:长镜头知乎 编辑:程序博客网 时间:2024/05/17 03:24

最近两天,再修改实验室的项目bug的时候,遇到了Map的get(key)方法得不到value的情况。分析了一下原因,原来程序中用到的Map类型是HashMap,而Map的key的类型是自己定义的一个类,并且这个类的hashCode()方法被重写了,所以当一条键值对被put进Map之后,如果某一个key被改变之后,就会发生get(key)方法得不到value的问题。

现将Java中使用Map的时候,需要注意的地方记录一下。

1、尽可能使用常量作为key值,比如Integer和String。如果一定要用自己实现的类作为key,那么不要覆盖父类Object的hashCode方法,如果覆盖了Object的hashCode()方法,那么如果一不小心改掉了HashMap的key,就不可能根据改变后的key得到先前put进去的value。下面举一个例子:

import java.util.HashMap;import java.util.Map;class People{int height;int weight;public People(int height, int weight) {this.height = height;this.weight = weight;}@Overridepublic int hashCode() {return this.height + this.weight;}}public class Test {public static void main(String[] args) {Map<People, Integer> map = new HashMap<People, Integer>();People people = new People(175, 70);map.put(people, 10);System.out.println(map.get(people));people.height = 180;System.out.println(map.get(people));}}
输出结果:

10null

从上面输出的结果可以看出,第二条输出的是null。也就是说,当people这个key改变之后,就不可能根据改变了的key值获得前面put进去的value。



0 0