正如@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);
}
}