【问题标题】:JAVA: Generic type compile time constantJAVA:泛型编译时间常数
【发布时间】:2014-05-21 15:57:59
【问题描述】:

我有一个抽象的泛型类,它需要一个数字常量来初始化一个数组。当我使用该泛型类时,我在编译时知道数组的大小。有什么方法可以实现吗?

abstract class Node<T, MagicN> {

    private T parent    = null;
    private T[] child   = (T[]) new Object[MagicN];

    //some methods that rely on the initialized array.

}
final class ConcreteNode extends Node<ConcreteNodeType, 2> {

}

在这个例子中,ConcreteNode 类有 2 个孩子。

【问题讨论】:

  • 什么?你的问题真的不清楚。
  • 这是无效的:private T[] child = (T[]) new Object[MagicN];
  • 我想用一个通用常量值初始化数组。我无法更好地解释:(
  • 来吧,我知道这是无效的,这就是我将其命名为 MAGIC 的原因!这只是一个例子。
  • 你可以在构造函数中初始化,使用泛型类初始化不是一个好主意。 MagicN 其实是Integer

标签: java generics numbers constants


【解决方案1】:

您不能使用 Generic 作为模板。由于 Java 的代码优化是在运行时完成的,因此几乎没有理由进行这种编译时内联。

abstract class Node<T extends Node> {

    private final T parent;
    private final T[] child;

    Node(T parent, int size) {
        this.parent = parent;
        child = (T[]) new Object[size];
    }

    //some methods that rely on the initialized array.

}
final class ConcreteNode extends Node<ConcreteNode> {
     ConcreteNode(ConcreteNode parent) {
         super(parent, 2);
     }
}

【讨论】:

    【解决方案2】:

    你不能有值而不是泛型类型(或者你应该为你可能使用的每个值创建一个类...)
    我认为在你的情况下最好有一个构造函数,将这个值作为参数,例如:

    abstract class Node<T> {
    
        private T parent    = null;
        private int MagicN = 0;
        private T[] child   = null;
    
        protected Node(int MagicN)
        {
            this.MagicN = MagicN;
            this.child = (T[]) new Object[MagicN];
        }
    
        //some methods that rely on the initialized array.
    
    }
    
    final class ConcreteNode extends Node<ConcreteNodeType> {
        public ConcreteNode()
        {
            super(2);
        }
    }
    

    就性能而言,您尝试执行的操作与此示例之间没有区别,因为您的子数组是在对象上下文中初始化的,而不是静态的。

    【讨论】:

      【解决方案3】:

      为什么不这样做呢?

      abstract class Node<T> {
          private T parent    = null;
          private T[] child;
      
          public Node(int childCount) {
              child = (T[]) new Object[childCount];
      
          //some methods that rely on the initialized array.
      
      }
      final class ConcreteNode extends Node<ConcreteNodeType> {
          public ConcreteNode()
          {
              super(2);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多