我已经看到很多关于是否可以在未指定默认类型的情况下指定默认类型的问题。答案似乎是否定的。我的问题是,如果您的类 header 需要一个类型参数,而您根本没有传递给它,那么它默认为什么?目的?采用 Queue 的简单 Linked Node 实现(缩写):
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
}
当然,我必须转换所有违背泛型目的的东西,但它真的将我的数据项默认为对象以允许它们全部进入队列吗?这是我能想到的唯一解释,但我想确认一下,因为我找不到具体的书面说明,情况确实如此。
最佳答案
是的,如果你不指定类型,它默认为Object
。 但是您应该避免使用原始类型,而应尽可能使用泛型,因为泛型在编译时提供更严格的类型检查。
您必须知道类型参数只保留到运行时,即在运行时类型参数被删除,这个过程称为Type Erasure .
关于java - 如果一个类是用泛型类型参数声明的,并且它在没有指定类型的情况下被实例化,它是否默认为 Object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20436661/