Question

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.

Was it helpful?

Solution

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);
        }
    }

OTHER TIPS

For these cases, and I see alot of them. I normally convert them to all uppercase and then compare as it is the easiest way to do so. I am assuming Linux shell for this as you did not mention a language.

s1=$(echo "This is a string" |tr '[:upper:]' '[:lower:]')
s2=$(echo "this is a string" |tr '[:upper:]' '[:lower:]')

[ "$s1" == "$s2" ] && echo "They will compare with AnY Case USED"

Feel free to post more information and I will modify my answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top