1

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.

4

2 回答 2

1

正如@Matt 所说,有两种方法可以在添加之前将它们更改为小写的大写,这样它就不允许您添加相同的字符串两次

public static void main(String[] args) {
        Set<String> mySet = new HashSet<String>();
        mySet.add("fdfd".toUpperCase());
        mySet.add("Fdfd".toUpperCase());
        System.out.println(mySet);
    }

我能想到的第二种方法是为字符串创建一个 Wrapper 类并定义它

eqauls() 和 hashCode()

根据您的字符串如下

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

}

并按如下方式运行

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);
        }
    }
于 2013-10-27T04:31:50.170 回答
0

对于这些情况,我看到了很多。我通常将它们全部转换为大写,然后进行比较,因为这是最简单的方法。我为此假设 Linux shell,因为您没有提到语言。

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"

随时发布更多信息,我将修改我的答案。

于 2013-10-27T04:04:03.937 回答