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)); } }
source share