【问题标题】:If a class is declared with a generic type parameter, and it's instantiated without specifying the type, does it default to Object?如果使用泛型类型参数声明一个类,并且在没有指定类型的情况下对其进行实例化,那么它是否默认为 Object?
【发布时间】:2013-12-07 02:01:19
【问题描述】:

我已经看到很多关于如果没有指定默认类型是否可以指定的问题。答案似乎是否定的。我的问题是,如果您的类头需要一个类型参数,而您根本不传递它,那么它的默认值是什么?目的?以一个队列的简单链接节点实现(缩写):

public class ListQueue<T> implements Queue<T>
{
   private Node<T> first;
   private Node<T> last;

   public void enqueue(T item)
   {
      Node<T> x = new Node<T>(item);
      if (isEmpty())
      {
         first = x;
         last = x;
      }
      else
      {
         last.next = x;
         last = x;
      }
   }

   public T dequeue()
   {
      if (isEmpty())
      {
         throw new IllegalStateException("Queue is empty");
      }
      T item = first.data;
      first = first.next;
      if (isEmpty())
      {
         last = null;
      }
      return item;
   }
}

public class Node<T>
{
   public T data;
   public Node<T> next;

   public Node(T data)
   {
      this(data, null);
   }

   public Node(T data, Node<T> n)
   {
      this.data = data;
      next = n;
   }
}

然后在我的测试驱动程序中,我似乎能够对任何类型的数据进行入队/出队:

public static void main(String[] args)
{
   ListQueue myQueue = new ListQueue();  // key point: no type specified

   myQueue.enqueue("test");
   myQueue.enqueue(2);
   myQueue.enqueue(new Date());

   System.out.println(myQueue.dequeue()); // prints "test"

   int result = 2 + (Integer)myQueue.dequeue();
   System.out.println(result); // prints 4

   Date now = (Date)myQueue.dequeue();
   System.out.println(now); // prints current date
}

当然,我必须强制转换所有违背泛型目的的东西,但它真的将我的数据项默认为对象以允许它们全部进入队列吗?这是我能想到的唯一解释,但我想确认一下,因为我找不到具体写出来的情况。

【问题讨论】:

    标签: java object generics linked-list queue


    【解决方案1】:

    是的,如果您不指定类型,则默认为Object。 但是您应该避免使用原始类型,并且应该尽可能使用泛型,因为泛型在编译时提供更严格的类型检查。

    您必须知道类型参数仅保留到运行时,即在运行时类型参数被擦除,此过程称为Type Erasure。

    【讨论】:

    • +1 并注意它默认为其上限,在本例中为Object。因此,public class ListQueue&lt;T extends Number&gt; 将默认为 Number。
    【解决方案2】:

    这就是 java 1.4 过去的工作方式。泛型是作为 java 1.5 的一部分引入的,以便我们可以更好地控制放入 Collections 的内容和检索的内容。这样做是为了最大限度地减少运行时可能出现的错误。

    要回答您的问题,它确实默认为反对。实际上,它总是对象(至少在运行时)。您使用的泛型东西只是我们在编译时的安全网。一旦 java 类被编译成字节码,所有泛型的东西都会被编译器删除。所以你的运行时代码看起来就像你从来没有使用过泛型一样。

    【讨论】:

      【解决方案3】:

      它不会“默认”任何东西。原始类型不同于任何参数化类型。

      ListQueue 与 ListQueue&lt;Object&gt; 不同。示例:

      ListQueue<String> foo;
      ListQueue myQueue = foo; // compiles
      ListQueue<Object> myQueue2 = foo; // doesn't compile
      

      但是,就原始类型的方法的参数和返回类型而言,它们都变成了非泛型,并且 T 降低到了上限。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多