how to write case-insensitive collection(HashMap)?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Chandra_Mouli
Posted On:   Thursday, January 10, 2002 02:56 AM

hai

I want write a java program so that it should be case-insensitive.

ex:

MyHashMap map = new MyHashMap();

map.put("KEY1","val1");

map.get("key1");



The key should be same case as I given in MyHashMap but when I tried to get value using small case key it has to come.

key may even mixed case also.

Can any body help in this regard with example program?
Plese mail solution to this mail ID :
mouliindia@yahoo.co.in

Re: how to write case-insensitive collection(HashMap)?

Posted By:   Christopher_Schultz  
Posted On:   Thursday, January 10, 2002 05:22 AM

So, you need a HashMap which is case-insensitive with respect to the key, but you need to preserve the case when reading the keys?



You'll have to write your own HashMap implementation, then. If you didn't care about the case of the keys and could store them, say, in lower-case only, then you could subclass the existing one:




public class CaseInsensitiveHashMap
extends HashMap
{
public void put(Object key, Object value)
{
if(!(key instanceof String))
throw new IllegalArgumentException("Key must be a String");

super.put(((String)key).toLowerCase(), value);
}

public Object get(Object key)
{
if(!(key instanceof String))
throw new IllegalArgumentException("Key must be a String");

return(super.get(((String)key).toLowerCase()));
}
}



This Map may break some of the contract of the Map class -- you'll have to document that so that client code knows what to expect.



Hope that helps,

-chris
About | Sitemap | Contact