0

I would like to get the value of a byte inside a Map object.

Map<String, Object> data = new HashMap<>();
data.put("foo", new byte[]{4});

System.out.println(data.get("foo"));

What I'm getting is like this... [B@1a779dce

Please help me.

Mnick
  • 233
  • 3
  • 15
  • 3
    that is what the `toString()` implementation for `byte[]` class look like, what is your expectation – jmj Jun 09 '14 at 04:52
  • I would like to get the value of the byte which is 4. – Mnick Jun 09 '14 at 04:54
  • `data.get("foo")` returns a `byte[]` which isn't a `byte`. You will have to specify an index. – awksp Jun 09 '14 at 04:54
  • The answer this duplicates isn't an _exact_ duplicate, as that one talks about `int[]` instead of `byte[]`. But the same concept applies. Basically, you _are_ getting back the `byte[]`, but it's not printing as you'd expect. – yshavit Jun 09 '14 at 04:56
  • data.get("foo") is an Object type. – Mnick Jun 09 '14 at 04:59
  • So cast it, because you know what its actual type is? – awksp Jun 09 '14 at 05:03

2 Answers2

1

As @JigarJoshi mentioned in his comment, that is what the toString() implementation for byte[] class look like. When you do System.out.println on a byte[], the toString() method gets called to convert it to a String before printing.

If you want to read the individual bytes, you will have to loop through the return value.

byte[] ba = (byte[]) data.get("foo");
for (byte b: ba) {
    System.out.println(b);
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

As you are adding Object to Map not byte[] so you need to cast it.

Map<String, Object> data = new HashMap<>();
data.put("foo", new byte[]{4,3,1,2});
System.out.println(Arrays.toString((byte[])data.get("foo")));

OUTPUT

[4,3,1,2]
akash
  • 22,664
  • 11
  • 59
  • 87