Class which accepts number ofkey-value pairs but doesn't allow duplicate enrty of combination.
4 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   vivek_puranik
Posted On:   Thursday, December 13, 2001 07:05 AM


I'm developing one application where I want to enter in a class, key-value pairs so that when a duplicate of key-value pair is not allowed to be added


Can anybody suggest a Class which allows a key-value pair to be added to it but it won't allow a duplicate key-value pair to get added?

Re: Class which accepts number ofkey-value pairs but doesn't allow duplicate enrty of combination.

Posted By:   Anonymous  
Posted On:   Saturday, January 12, 2002 08:20 AM

There are no predefined class, as other people has already said.

I would create my own version of either HashMap or TreeMap (it depends if you prefer not sorted or sorted), overriding just the put method. The new put will check if a value already exists for the given key. If not it will insert the key, otherwise it will throw an error.


Regards

Re: Class which accepts number ofkey-value pairs but doesn't allow duplicate enrty of combination.

Posted By:   Anonymous  
Posted On:   Saturday, January 12, 2002 05:35 AM

There is no class which can directly solve your problem. But you can achieve what you are looking for by using HashSet.

Make your own class which as a key , value as its member variable. Implement its override its default equals and hashCode methods. And store the object of this class in your HashSet class.

Re: Class which accepts number ofkey-value pairs but doesn't allow duplicate enrty of combination.

Posted By:   Christopher_Schultz  
Posted On:   Thursday, December 13, 2001 12:57 PM

There's no existing class (at least not in the Java API) that does what you want to do.



The java.util.Hashtable and friends will let you have only one entry for any given key, but it does not allow multiple values for the same key, directly.



You could build your own dfata structure to do this, which is basically a hashtable of lists:



Hashtable:
Key Value
key1 list [value1, value2, value3]
key2 list [value1, valud2, value3]
key3 list [value1, valud2, value3]

Then, when you perform an 'insert', you can scan the list in the table for your key and see if the new value already exists. If it does, either throw an exception or do nothing or whatever you want to do.



If you're really paranoid, you could use a Set instead of a List to store your values.



Hope that helps,

-chris

Re: Class which accepts number ofkey-value pairs but doesn't allow duplicate enrty of combination.

Posted By:   Anonymous  
Posted On:   Thursday, December 13, 2001 07:13 AM

java.util.Hashtable
About | Sitemap | Contact