How will Hashmap key behave if hash code is overridden such that it returns only a constant number?

前端 未结 3 1076
一向
一向 2021-01-19 05:49

I have a small question about Java Hashmap. If I override the hashCode method such that:

@Override
public int hashCode(){
  return          


        
3条回答
  •  广开言路
    2021-01-19 06:20

    Whether it appears as a linked list or not is debatable as it does not state in the documentation. However, it will certainly keep all items with unique keys (i.e. keys that return true to the equals method).

    class Nine {
    
        final String value;
    
        public Nine(String value) {
            this.value = value;
        }
    
        @Override
        public int hashCode() {
            return 9;
        }
    
        @Override
        public boolean equals(Object it) {
            return it instanceof Nine && ((Nine) it).value.equals(value);
        }
    
        @Override
        public String toString() {
            return value;
        }
    }
    
    class AlwaysNine extends Nine {
    
        public AlwaysNine(String value) {
            super(value);
        }
    
        @Override
        public boolean equals(Object it) {
            return it instanceof Nine;
        }
    }
    
    public void test() {
        System.out.println("Hello");
        Map testMap = new HashMap();
        testMap.put(new Nine("Nine"), "Nine");
        testMap.put(new Nine("nine"), "nine");
        testMap.put(new AlwaysNine("nIne"), "nIne");
        System.out.println(testMap);
    }
    

    prints

    {Nine=nIne, nine=nine}
    

    which proves that only overriding equals will force keys to seem to be the same ... as expected because hashCode is only used to pick the bucket in which to place the object.

提交回复
热议问题