5

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!

1
  • Commons Collections doesn't get the exposure it deserves...
    – Isaac
    Nov 23, 2012 at 10:53

6 Answers 6

8

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().

7

I wouldn't extend HashMap class, since in this case, it would lead to a violation of Liskov Substitution Principle because you alter behavior of a base class method.

Instead I would use composition:

Create your CustomHashMap class implementing Map interface and HAVING an HashMap field. And redeclare every methods present in HashMap class, adding a delegation to the original HashMap for each except for the put() method => throw an exception if entry already exists.

0
2

Several ideas:
A. Throw an exception that extends RuntimeException in your class that extends HashMap.
B. Provide some sort of MapWrapper that will recieve a Map as parameter, will have get, put, and some other methods , with signatures that suits you more.

5
  • @zaske Liskov violation here also.
    – Mik378
    Nov 23, 2012 at 11:06
  • @Mik378, A here violates LSP; B doesn't. But B is already available within Commons Collections (see my answer), no need to reinvent the wheel.
    – Isaac
    Nov 23, 2012 at 11:12
  • @Isaac Yes Isaac, sorry, I was talking about only your A proposal. I do agree with your solution from commons-collection.
    – Mik378
    Nov 23, 2012 at 11:14
  • @Mik378 The A proposal wasn't mine. This is @zaske's answer here :-)
    – Isaac
    Nov 23, 2012 at 11:16
  • @Isaac Indeed! I have salt in the eyes :)
    – Mik378
    Nov 23, 2012 at 11:18
1

The javadoc for Map#put states:

throws IllegalArgumentException if some property of the specified key or value prevents it from being stored in this map

I think your use case falls into that category and I would therefore use that possibility. Since it is an unchecked exception, you could use composition, wrap a HashMap and throw an IllegalArgumentException on duplicates in the put method.

0

You could throw an Exception that extens RuntimeException.

10
  • 2
    Hey you downvoter, my answer is valid. Give reason why you downvote
    – AlexWien
    Nov 23, 2012 at 10:53
  • 1
    I wasn't the downvoter, but I believe that the reason for downvoting was that you proposed a solution that would require the OP to explicitly code the duplicity check themselves, whereas the OP clearly states that they're looking for a mechanism that will do it automagically.
    – Isaac
    Nov 23, 2012 at 10:59
  • 1
    @AlexWien I didn't downvote but you would violate Liskov Substitution Principle.
    – Mik378
    Nov 23, 2012 at 11:00
  • @Mik No not realy, if he does not derive, but uses composition whch in most cases is the favorable technic, then he still cam implement the map interface, and throwing an runtime exception.
    – AlexWien
    Nov 23, 2012 at 11:02
  • @isaac the OP statet that he dont wantbto check for dupps outside the class. But will do inside
    – AlexWien
    Nov 23, 2012 at 11:06
0

You can extend HashMap and throw an Exception that is subclass of RuntimeException or one of the Exception already thrown by the put method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.