I am creating a program in Java with TreeSet<Object>
and HashSet<Objcet>
and I want to add some strings to these sets, but I have a problem:
When I add the strings, e.g I add "Brian", "brian", "BRIAN", "BrIaN", all those strings should mean the same. But TreeSet or HashSet don't consider them equal.
How can I make them treat my strings as equal by ignoring any difference in uppercase or lowercase letters?
Thanks.
There are two ways to do it as @Matt stated either change them to uppercase of lowers case before adding so it will not allow you to add same string twice
public static void main(String[] args) {
Set<String> mySet = new HashSet<String>();
mySet.add("fdfd".toUpperCase());
mySet.add("Fdfd".toUpperCase());
System.out.println(mySet);
}
Second way I can think of is to create a Wrapper class for string and define its
eqauls() and hashCode()
based on your string as follows
package com.sample;
public class StringWrapper {
String myString;
StringWrapper(String newString) {
this.myString = newString;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((myString == null) ? 0 : myString.toUpperCase().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StringWrapper other = (StringWrapper) obj;
if (this.myString.equalsIgnoreCase(other.myString)) {
return true;
}
return true;
}
}
and run it as follows
public static void main(String[] args) {
Set<StringWrapper> mySet = new HashSet<StringWrapper>();
mySet.add(new StringWrapper("brain"));
mySet.add(new StringWrapper("Brain"));
for (StringWrapper s : mySet) {
System.out.println(s.myString);
}
}