Using String (byte []) as the key to the map

I have a program that retrieves identifiers from a database returned as byte[] . I want to use these identifiers (byte arrays) as keys to the map. This does not work by default because it compares “equality of objects” rather than “equality of content”.

The next thing I tried, which seemed to work, was to create an instance of String with the constructor new String(byte[]) . Although this seems to work, I know that I am doing some potentially tricky things. I do not specify an encoding that relies on all system defaults. I also don't know if all byte sequences will have a representation in each encoding.

Is "converting" byte[] to String to safely use map.put() and map.get() ? Are there any extreme cases that I don’t consider when this approach inadvertently creates a collision (where 2 different byte[] with different content can become the same String ).

Note. The map is stored in memory and works only for one application launch. A simple wrapper class that I wrote to make my life easier if this approach is viable:

 public class Cache { Map<String, Set<String>> cache = new HashMap<String, Set<String>>(); public Cache() {} public void put(byte[] key, Set<String> value) { cache.put(new String(key), value); } public Set<String> get(byte[] key) { return cache.get(new String(key)); } } 
+4
source share
2 answers

You should Biginteger use Biginteger . It has a BigInteger constructor (byte []) and has an efficient comparison system.

+6
source

Could you create a simple wrapper around your byte[] array?

Something similar to:

 public class CacheKey { private final byte[] key; public CacheKey(byte[] key) { this.key = key; // You may want to do a defensive copy here } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheKey cacheKey = (CacheKey) o; return Arrays.equals(key, cacheKey.key); } @Override public int hashCode() { return key != null ? Arrays.hashCode(key) : 0; } } 

And use this as a card key? This will be a little easier than using the built-in String object and makes the key type really clear.

+2
source

All Articles