这是我的代码:
public enum DecisionType {
REFUSAL,
GRANT_OF_PROTECTION,
PARTIAL_REFUSAL;
}
public class DocumentComposition<T extends Enum<DecisionType>> extends TreeMap<DocumentType, Object> {
@Override
public Object put(DocumentType key, Object value) {
if (key.getDecisionType() != ) {
return null;
}
return value;
}
}
DocumentComposition map = new DocumentComposition<DecisionType.REFUSAL>();
我需要我的 Map 仅包含具有 DecisionType 枚举的特定值的元素。我该如何实现这一目标?我的测试应该是什么样子?
最佳答案
我理解正确吗?您想要一个仅接受特定 DecisionType 的 DocumentType 实例的 DocumentComposition 吗? 我的解决方案部分:
- 您不需要为此使用泛型,而是需要在构造函数中提供内部变量。
在重写的 put 方法中,您一定不要忘记调用 super,否则您的 TreeMap 将永远不会获取任何元素。
public class DocumentComposition extends TreeMap<DocumentType, Object> { private DecisionType acceptedDecisionType; public DocumentComposition(DecisionType acceptedDecisionType) { this.acceptedDecisionType = acceptedDecisionType; } @Override public Object put(DocumentType key, Object value) { if (key.getDecisionType() != acceptedDecisionType) { return null; } return super.put(key, value); // do not forget to call super, otherwise your TreeMap is not filled } }
现在您可以使用 map 了:
public static void main( String args[])
{
DocumentComposition dc=new DocumentComposition(DecisionType.REFUSAL);
dc.put(new DocumentType(DecisionType.REFUSAL), "refusalDoc");
dc.put(new DocumentType(DecisionType.PARTIAL_REFUSAL), "partialRefusalDoc");
System.out.println(dc);
}
只有 refusalDoc 会出现在 map 中。
关于java - 如何检查 Java 中的泛型枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55280087/