如何检查Java中的泛型枚举?

如何检查Java中的泛型枚举?,java,generics,enums,Java,Generics,Enums,这是我的密码: 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 k

这是我的密码:

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>();
公共枚举决策类型{
拒绝
给予保护,
部分拒绝;
}
公共类DocumentComposition扩展树映射{
@凌驾
公共对象put(DocumentType键、对象值){
if(key.getDecisionType()!=){
返回null;
}
返回值;
}
}
DocumentComposition map=新的DocumentComposition();

我需要我的映射只包含DecisionType枚举的某个值的元素。我如何做到这一点?我的测试应该是什么样子?

我理解得对吗?您想要一个DocumentComposition,它只接受特定DecisionType的DocumentType实例? 我的解决方案部分:

  • 您不需要为此使用泛型,而是在构造函数中提供一个内部变量
  • 在重写的put方法中,千万不要忘记调用super,否则树映射将永远不会得到任何元素

    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
        }
    }
    

    地图中只有拒绝文档。

    为什么不扩展TreeMap?为什么不扩展TreeMap?如果希望映射“仅包含具有DecisionType enum特定值的元素”,在映射之前,只需使用“If”语句检查它们的类型,并决定是否要将其放置。您也可以将属性添加到枚举中,但如果不了解枚举和筛选背后的逻辑,现在很难再添加属性。感谢您不辞劳苦地在此提供帮助。你是对的,当然,这是处理这种情况的简单方法。我只是想,也许,有一种优雅的方法可以用泛型来做。。。不知何故,从设计的角度来看,这是我想到的第一件事。我不确定这里是否可以使用泛型,因为您希望指定枚举值而不是类型作为泛型参数。是的,确实存在混淆。不过很遗憾。
        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);
        }