Elroy Jetson Elroy Jetson - 15 days ago 6
Java Question

Why are the values in my hash map different than what was put in?

I have a hash map that seems to be altering the values that I store in it. Almost all of my keys are mapping correctly; however, there are about 4 or 5 keys whose values are completely different in the

entrySet()
than what was actually put inside of them. I'm at a complete loss.

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;

}


I noticed a few of my conditions were failing for some reason, then when I printed out the
entrySet()
I noticed keys like 'i' were being mapped to 4160, even though I clearly put
010100
. Also, 'j' gives me a bogus result with 4160 too. The others are fine...and then once again characters 'w' and a few others are mapped to 4 digit numbers that begin with 4.

Here's the whole entry set:

[ =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]


As you can see, 't', and 's' are not as intended as well as the others previously mentioned. What's going on?

Answer

As you've discovered, there's an issue with putting a leading zero in front of an integer; Java will treat it as an octal number, which is base-8.

This is the first problem. The numbers you're putting in there are not base-2 like you intended, but they are base-8.

That's easily solved; you would simply have to ensure that the numbers are parsed as binary when you place them into your map.

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

Printing these numbers will give you their full integer representation. This is the second problem; printing out collections does not translate or format the data in any other form besides the standard numerical-type representation.

If you want to print them as hex values, you'll need to make use of Integer.toBinaryString.

This too is easily accomplished with Java 8's Stream API.

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