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 6hashcode 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}
任何人都可以帮助我理解程序和输出中的两件事:
map对象打印的数据,它内部是如何决定顺序的? 例如。它正在打印序列 p, a, d, e, k。
entry.hashcode() 和entry.key().hashcode() 有什么区别? 请引用输出来解释差异。
最佳答案
据我所知,HashMap 不能保证 Entry 或键的顺序。如果您想对它们进行排序,您将需要 TreeMap 或链接 map 。 See here. 。 HashMap 根本没有顺序。
我已经评论了您 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/