简体   繁体   中英

Java HashMap Key Confusing

private static final HashMap<StringFirstFourSymbolsHashCode, Product> FIRST_FOUR_SYMBOLS_HASH_CODE_PRODUCT_HASH_MAP = new HashMap<StringFirstFourSymbolsHashCode, Product>() {{
        put(new StringFirstFourSymbolsHashCode("121"), new Product("prod1", "100500"));
        put(new StringFirstFourSymbolsHashCode("45631232"), new Product("prod2", "400500"));
        put(new StringFirstFourSymbolsHashCode("6442112"), new Product("prod3", "20500"));
        put(new StringFirstFourSymbolsHashCode("4562121"), new Product("prod4", "22500"));
        put(new StringFirstFourSymbolsHashCode("4321"), new Product("prod5", "1020"));
    }};

StringFirstFourSymbolHashCode overrided methods

@Override
public int hashCode() {
    int hashCode = 0;
    for(Character character : string.toCharArray()){
        hashCode += character;
    }
    return hashCode;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (!(obj instanceof StringFirstFourSymbolsHashCode)) {
        return false;
    }
    StringFirstFourSymbolsHashCode stringFirstFourSymbolsHashCode = (StringFirstFourSymbolsHashCode)obj;
    return string.equals(stringFirstFourSymbolsHashCode.string);
}

When I out elements from HashMap they outs very strange. How I can see HashMap's keys ordered by increase, but why after 410 outs 202

> StringHashCodeLength HasMap Iterator
> StringFirstFourSymbolsHashCode{string='121,
> hashCode=148}=Product:name='prod1, cost='100500}
> StringFirstFourSymbolsHashCode{string='6442112,
> hashCode=356}=Product:name='prod3, cost='20500}
> StringFirstFourSymbolsHashCode{string='4562121,
> hashCode=357}=Product:name='prod4, cost='22500}
> StringFirstFourSymbolsHashCode{string='45631232,
> hashCode=410}=Product:name='prod2, cost='400500}
> StringFirstFourSymbolsHashCode{string='4321,
> hashCode=202}=Product:name='prod5, cost='1020}

Please, explain how it works

try the following

 private static final SortedMap<StringFirstFourSymbolsHashCode, Product> FIRST_FOUR_SYMBOLS_HASH_CODE_PRODUCT_HASH_MAP =
 new  SortedMap<StringFirstFourSymbolsHashCode, Product>()

you just change HashMap with SortedMap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM