HashMap:为什么我能够获得一个'key'的'value',它是一个类型City类,不会覆盖equals()或hashcode()方法?

时间:2012-04-23 08:54:00

标签: hashmap override

根据Kathy Sierra SCJP 6.0书(Chaper 7:Generics and Collections,Pg.583,Using Maps),我需要覆盖类的equals()和hashcode()方法,这些方法的对象我想用作关键字,否则我无法找到该密钥的值。

但根据我的代码,我能够获得价值。为什么呢?

import java.util.*;

class City {
    String name;

    City(String name) {
        this.name = name;
    }
}

public class MyClass {

    public static void main(String[] args) {

        Map<Object, Object> map = new HashMap<Object, Object>();
        City c1 = new City("NewYork");
        map.put(c1, "Fashion Capital");
        System.out.println(map.get(c1));
    }

}

//输出是:“时尚之都”

0 个答案:

没有答案