2016-11-21 26 views
0

我有一個哈希映射,似乎正在改變我存儲在其中的值。幾乎所有的密鑰都映射正確;然而,entrySet()中有大約4或5個鍵的值完全不同於實際放入其中的值。我完全喪失了。爲什麼我的哈希映射中的值與放入的值不同?

public static void main(String args[]){ 
    HashMap<Character, Integer> map = make_map(); 
    System.out.print(map.entrySet()); 

} 

public static HashMap<Character,Integer> make_map(){ 
    HashMap<Character, Integer> map = new HashMap<>(); 


    map.put('a',100000); 
    map.put('b',110000); 
    map.put('c',100100); 
    map.put('d',100110); 
    map.put('e',100010); 

    map.put('f',110100); 
    map.put('g',110110); 
    map.put('h',110010); 
    map.put('i',010100); 
    map.put('j',010110); 

    map.put('k',101000); 
    map.put('l',111000); 
    map.put('m',101100); 
    map.put('n',101110); 
    map.put('o',101010); 

    map.put('p',111100); 
    map.put('q',111110); 
    map.put('r',111010); 
    map.put('s',011100); 
    map.put('t',011110); 

    map.put('u',101001); 
    map.put('v',111001); 
    map.put('w',010111); 
    map.put('x',101101); 

    map.put('y',101111); 
    map.put('z',101011); 
    map.put(' ',000000); 



    return map; 

} 

我注意到我的幾個條件沒有出於某種原因,然後當我打印出來的entrySet()我發現像鑰匙「我」都被映射到4160,即使我明確提出010100。另外,'j'也給了我一個4160的虛假結果。其他人都很好......然後再次字符「W」和其他幾個人被映射到與4

開始這裏的整個條目集4個數字:

[ =0, a=100000, b=110000, c=100100, d=100110, e=100010, f=110100, g=110110, h=110010, i=4160, j=4168, k=101000, l=111000, m=101100, n=101110, o=101010, p=111100, q=111110, r=111010, s=4672, t=4680, u=101001, v=111001, w=4169, x=101101, y=101111, z=101011] 

,你可以看到't'和's'不像其他前面提到的那樣。這是怎麼回事?

+3

從0開始的數字文字被解析爲八進制數字(基數8)。也許你應該使用'HashMap '。 – Eran

+1

重複說明*爲什麼*結果會以這種方式出現,但實際上並沒有提供任何解決方法來解決此問題。 – Makoto

回答

2

正如你已經發現,有在整數前放置一個前導零的問題; Java會將其視爲一個八進制數字,它是基數爲8的數字。

這是第一個的問題。你放在那裏的數字是而不是 base-2就像你想的那樣,但他們 base-8。

這很容易解決;您只需確保將數字放入地圖時將數字解析爲二進制。

map.put('a', Integer.parseInt("100000", 2)); 

打印這些數字會給你充分的整數表示。這是第二個的問題;除了標準數值型表示之外,打印出集合不會以任何其他形式翻譯或格式化數據。

如果要將它們打印爲十六進制值,則需要使用Integer.toBinaryString

這也很容易用Java 8的Stream API完成。

map.entrySet().forEach((entry) -> System.out.printf("%s=%s ", entry.getKey(), Integer.toBinaryString(entry.getValue()))); 
1

你看這個結果,因爲你的價值觀開始0,並表示爲八進制數字,基地8