Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap with uniqueness check

I have a class with several key-value lists. Each key (within a list) should be unique, so I use HashMap. When somewhere in the code I add a new item to a list, I am using HashMap's put(K, V). I'd like my code to throw an exception if an attempt is made to add an item with already existing key. And, because such adding is performed in many places in the program, I would like to avoid adding checking in each of them. So it should be the list class itself that would not allow replacing existing key-value pair.

I thought of extending the HashMap class with my own one, which would perform such a check and throw an exception. However, HashMap's put does not throw exceptions, so I cannot do it either.

What would be a good approach to achieve such behaviour? I am ready to replace HashMap with something better, but I need it to be fast in both adding and retrieving items.

Update: Thanks all for many nice suggestions. Since I am a complete newbie in Java, I now need to learn a lot to be able to choose the best one :) Anyway, I am grateful for getting so many options within a lunch-break!

like image 976
texnic Avatar asked Nov 23 '12 10:11

texnic


1 Answers

You can use Commons Collections for this, something like:

Map map = MapUtils.predicatedMap(new HashMap(), PredicateUtils.uniquePredicate(),
             null);

This will create a Map instance that will throw an exception whenever you try inserting a key-value pair when the same key already exists.

Of course, you can customize this behaviour by constructing your own Predicate instance and using it instead of PredicateUtils.uniquePredicate(). Your own Predicate can do whatever you need it to do, so for example, it could throw a different type of exception than the one thrown by the default uniquePredicate().

like image 176
Isaac Avatar answered Nov 01 '22 09:11

Isaac