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

标签 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 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/

相关文章:

java - Java 动态对象数组

java - 避免使用具有双扩展类的泛型进行未经检查的强制转换?

java - 通过 List<?> 从 List<subclass> 向上转换为 List<superclass>

enums - 如何处理 flat_map 中的单个元素?

java - 骰子声明错误

java - CLI 测试失败,传入 IDE - 加载资源

java - android.view.InflateException : Binary XML file line #51: Error inflating class com. android.internal.widget.DialogTitle

dictionary - Elixir获得的值在 map 中不为空

java - Jersey 与 RestEasy - JAX-RS XML 集合根元素名称更改

c# - 使用递归和泛型创建快速排序