如果使用泛型类型参数声明一个类,并且在未指定类型的情况下实例化它,它是否默认为Object?

Cpt*_*rkt 3 java generics queue linked-list object

我已经看到了很多关于是否可以指定默认类型的问题(如果没有指定).答案似乎是否定的.我的问题是,如果你的类头需要一个类型参数,你根本就没有把它传递一个什么它默认为?宾语?采用Queue的简单链接节点实现(缩写):

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

当然,我必须抛出一切违背泛型的目的,但它是否真的将我的数据项默认为Objects以允许它们全部进入队列?这是我能想到的唯一解释,但我想确认一下,因为我无法找到它具体写出来就是这种情况.

Kon*_*kov 5

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

必须知道类型参数仅在运行时保留,即在运行时类型参数被擦除且此过程称为类型擦除.

  • +1并注意它默认为*上限*,在这种情况下是`Object`.因此,对于`public class ListQueue <T extends Number>`,它将默认为`Number`. (5认同)