• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Map that doesn't allow overwriting existing keys

 
Ranch Hand
Posts: 15304
6
Mac OS X IntelliJ IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there a Map implementation or a different Map like interface that will throw an exception if you try and insert a key/value where the key already exists? I've looked through the API but can't seem to find one.

Thanks.
[ April 03, 2006: Message edited by: Gregg Bolinger ]
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not in the standard libraries, as far as I know. A quick and hopefully-not-too-dirty solution is:
It would probably be nicer to instead make this a decorator that could wrap any Map. A quick way to achieve that is by making a concrete implementation of org.apache.commons.collections.map.AbstractMapDecorator, very much like the code above. Note that there are other ways to change the data in a Map besides put(), and you will need to decide whether it's necessary to guard against all possible illicit changes to the data, or just the most common ones (via put()). Here's one loophole:

Plugging little holes like this one may take a bit more work and analysis, but it may not really be necessary for your application. Depending on how you intend to use it, and how much time you want to spend on it.
 
They gave me pumpkin ice cream. It was not pumpkin pie ice cream. Wiping my tongue on this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic