byte[] array as HashMap key?

T

Timo Nentwig

Hi!

Is there any way to use a byte[] array as a HashMap key? Like

Map m = new HashMap();
m.put(new byte[]{'a','b','c','d'}, new Foo());

and look up:

m.get(new byte[s, o, m, e]);

The above won't work. I want to prevent creating String objects but no way
to do this, is there?
 
K

Kevin McMurtrie

Timo Nentwig said:
Hi!

Is there any way to use a byte[] array as a HashMap key? Like

Map m = new HashMap();
m.put(new byte[]{'a','b','c','d'}, new Foo());

and look up:

m.get(new byte[s, o, m, e]);

The above won't work. I want to prevent creating String objects but no way
to do this, is there?

You can create a thin wrapper to implement equals(Object) and hashCode()
on the contents of an array. The class java.util.Arrays can help with
some of the work.

If you're mostly dealing with constants, then definitely use Strings.
The String class is optimized for use in hashing maps. The only part
that sucks is using StringBuffer or char[] to create new Strings.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top