gpt4 book ai didi

java - 在 Map 值中强制执行两种类型 - Java 泛型

转载 作者:行者123 更新时间:2023-12-01 18:35:58 25 4
gpt4 key购买 nike

我有一个情况,我需要使用Map,并将String作为键和StringLong 作为值。

由于它们不属于同一层次结构,我想我不能使用通配符。

那么有什么方法可以强制编译器接受 StringLong 作为值,否则我将不得不使用 Map 而没有 <强>泛型。

最佳答案

两种可能的解决方案要么使用 Map<String, Object>或者创建一个类似的类

public class DualValue {
private final String stringValue;
private final Long longValue;

public DualValue(final String stringValue) {
this.stringValue = stringValue;
this.longValue = null;
}

public DualValue(final Long longValue) {
this.stringValue = null;
this.longValue = longValue;
}

public String getStringValue() {
return stringValue;
}

public Long getLongValue() {
return longValue;
}

public boolean isString() {
return stringValue != null;
}

public boolean isLong() {
return longValue != null;
}

// next two are optional but should be implemented,
// if you ever want to use this class as key of a Map

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}

DualValue dualValue = (DualValue) o;

if (longValue != null ? !longValue.equals(dualValue.longValue) : dualValue.longValue != null) {
return false;
}
if (stringValue != null ? !stringValue.equals(dualValue.stringValue) : dualValue.stringValue != null) {
return false;
}

return true;
}

@Override
public int hashCode() {
int result = stringValue != null ? stringValue.hashCode() : 0;
result = 31 * result + (longValue != null ? longValue.hashCode() : 0);
return result;
}
}

并使用Map<String, DualValue> 。你是对的,除了使用 Object 之外,编译器无法以纯通用方法合并两个注定的类 hirachies。它是每个 Java 类的共同父类。即使可以,您可能也必须使用 value instanceof String 进行检查。或value instanceof Long如果您想对 Object 中不存在的值调用任何函数,则强制转换为其中之一.

关于java - 在 Map 值中强制执行两种类型 - Java 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22009630/

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