gpt4 book ai didi

java - 不区分大小写的映射键 Java

转载 作者:行者123 更新时间:2023-11-29 07:33:28 25 4
gpt4 key购买 nike

<分区>

我有一个 Map<String, Object>其中我需要 String 键不区分大小写

目前我正在包装我的 String我称为 CaseInsensitiveString 的 Wrapper 类中的对象其代码如下所示:

    /**
* A string wrapper that makes .equals a caseInsensitive match
* <p>
* a collection that wraps a String mapping in CaseInsensitiveStrings will still accept a String but will now
* return a caseInsensitive match rather than a caseSensitive one
* </p>
*/
public class CaseInsensitiveString {
String str;

private CaseInsensitiveString(String str) {
this.str = str;
}

public static CaseInsensitiveString wrap(String str) {
return new CaseInsensitiveString(str);
}


@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;

if(o.getClass() == getClass()) { //is another CaseInsensitiveString
CaseInsensitiveString that = (CaseInsensitiveString) o;
return (str != null) ? str.equalsIgnoreCase(that.str) : that.str == null;
} else if (o.getClass() == String.class){ //is just a regular String
String that = (String) o;
return str.equalsIgnoreCase(that);
} else {
return false;
}

}

@Override
public int hashCode() {
return (str != null) ? str.toUpperCase().hashCode() : 0;
}

@Override
public String toString() {
return str;
}
}

我希望能够得到 Map<CaseInsensitiveString, Object>仍然接受 Map#get(String)并返回值而无需执行 Map#get(CaseInsensitiveString.wrap(String)) .然而,在我的测试中,我的 HashMap每当我尝试这样做时都会返回 null 但如果我在调用 get() 之前包装字符串它确实有效

是否可以允许我的 HashMap接受 String 和 CaseInsensitiveString get 方法的参数并以不区分大小写的方式工作,而不管 String 是否存在。是否被包裹,如果是,我做错了什么?

作为引用,我的测试代码如下所示:

    Map<CaseInsensitiveString, String> test = new HashMap<>();
test.put(CaseInsensitiveString.wrap("TesT"), "value");
System.out.println(test.get("test"));
System.out.println(test.get(CaseInsensitiveString.wrap("test")));

并返回:

null
value

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com