作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个情况,我需要使用Map
,并将String
作为键和String
或Long
作为值。
由于它们不属于同一层次结构,我想我不能使用通配符。
那么有什么方法可以强制编译器接受 String
或 Long
作为值,否则我将不得不使用 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/
我是一名优秀的程序员,十分优秀!