Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

HashMap contains method without Case senstive generating problems

Status
Not open for further replies.

Pro79

Programmer
Dec 11, 2003
24
0
0
IN
Hi

I want to search for some key in HashMap but i am finding problem with case of text. there is a solution if i make an itertor then use equalsignorecase on string.

Is there any predefind solution defind in HashMap so that it can search key through contain without using case.


Rgds
Dinesh
 
A HashMap is a data holder that has no real knowledge of what it holds. The String method equalsIgnoreCase() is a method on an object - which may be what you want for your particular data in the HashMap - but what about if the object held a set of Integer objects - "case sensitivity" would not really be relevant would it ?

If your HashMap holds Strings, then just iterate through them, csting to a String object, anf calling equalsIgnoreCase() on each data member.

--------------------------------------------------
Free Database Connection Pooling Software
 
On the other hand, doing an iterator on a HashMap kind of defeats the purpose - you might as well use an ArrayList and save the extra overhead.

What if you did a toUpperCase() on the String when you set it as the key in the HashMap, and toUpperCase on the string in the get method?
 
If it is always case insensitive for the HashMap use in your application, then one work around would be always change the key to the same case when you put in the hashmap as well as the key that use to do the lookup. e.g.

Code:
HashMap map = new HashMap();
String key1 = "aBC";
String key2 = "def";

map.put(key1.toLowerCase(), key1);
map.put(key2.toLowerCase(), key2);

// to look for key "abc" case insensitive:
String lookupKey = "ABC";

// this will return String "aBC"
map.get(lookupKey.toLowerCase());
 
... or alternatively define your own key class which wraps a String and provides the behaviour, in terms of overriding equals() and hashCode(), you need. This key class could be re-used in any of the Map implementations.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
timw - that's a good idea but since String is final you would have to write a true wrapper. If you're doing that you might as well wrap/extend HashMap. It's much simpler that way in terms of re-use.

myenigmaself
"If debugging is the process of removing bugs, then programming must be the process of putting them in." --Dykstra
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top