Java - Hashmap检索序列

标签 java collections hashmap

import java.util.HashMap;
import java.util.Map.Entry;
public class TestString {
    public static void main(String[] args) {
        System.gc();

        String str = "deepak";
        int length = str.length();
        System.out.println("str " + str + " length " + length);

        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i=0; i<length; i++){
            char ch = str.charAt(i);
            if(map.containsKey(ch)){
                Integer val = map.get(ch);
                map.put(ch, val+1);
            }else{
                map.put(ch, 1);
            }
        }

        for (Entry<Character, Integer> entry : map.entrySet())
        {
            int hashCode = entry.hashCode();
            char key = entry.getKey();
           // int hash = hash();
            System.out.println("hashcode  " + hashCode + " hashcode of key>> " + entry.getKey().hashCode() + " key : " + key);
        }
        System.out.println(">>> " + map);
    }
}

Output :
str deepak length 6

hashcode 113 hashcode of key>> 112 key : p

hashcode 96 hashcode of key>> 97 key : a

hashcode 101 hashcode of key>> 100 key : d

hashcode 103 hashcode of key>> 101 key : e

hashcode 106 hashcode of key>> 107 key : k

>>> {p=1, a=1, d=1, e=2, k=1}

任何人都可以帮助我理解程序和输出中的两件事:

  1. map对象打印的数据,它内部是如何决定顺序的? 例如。它正在打印序列 p, a, d, e, k。

  2. entry.hashcode() 和entry.key().hashcode() 有什么区别? 请引用输出来解释差异。

最佳答案

  1. 据我所知,HashMap 不能保证 Entry 或键的顺序。如果您想对它们进行排序,您将需要 TreeMap 或链接 map 。 See here. 。 HashMap 根本没有顺序。

  2. 我已经评论了您 Java API 的链接,这很好地解释了这一点。但我会根据您的输出进行解释:

hashcode 113 hashcode of key>> 112 key : p

这意味着:条目的HashCode是113。你的Key的HashCode是112。你不打印你的条目的HashCode,它是1。条目的HashCode是用Key的HashCode和Value的HashCode计算出来的。那些 HashCodes 将被异或。

关于Java - Hashmap检索序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42692193/

相关文章:

java - 如何对对象列表进行排序

file - Gradle如何创建一个空的fileCollection?

java - 如何使用 HashMap 作为访问和复制列表中的项目的方法?

hash - 内部哈希和外部哈希之间的区别

java - 在 JTextArea 中停止水平滚动

java - 正则表达式接受带有单点的文件名

java - 自定义字符串长度比较器 : what's my mistake?

java - 如何在java中的嵌套映射中使用单个键来表示多个条目

java - 如何从其他 @Value 引用 @Value 中的某些内容

java - Spring MVC 中资源包的最佳方法是什么?