我编写了一个方法,该方法返回队列中包含值的ArrayList。队列ArrayList充满了Node对象,并且此类具有类型为T的参数值,这是我需要检索的数据。我做了一个getValue方法来做到这一点:
public T getValue() {
return value;
}
(该类的类型为<T>)。我的队列类中的方法是这样的:
public ArrayList getArray() {
ArrayList < T > onlyValues = new ArrayList<>();
for (int i = 0; i < queue.size(); i++) {
T tmp = (T)((queue.get(i)).getValue());
onlyValues.add(tmp);
}
return onlyValues;
}
如果在不进行强制转换(T)的情况下执行它,则会出现此错误:error: incompatible types: Object cannot be converted to T
为什么?我知道方法add接受类型为T的Object,而我在Node类中的方法返回一个T元素。
如果您将queue
变量声明为
private ArrayList <Node> queue;
并且Node
是通用的,那么您正在使用原始类型。将变量声明为:
private ArrayList <Node<T>> queue;
然后,您将不需要强制转换:
T tmp = queue.get(i).getValue();
您还缺少方法返回类型的type参数;
public ArrayList<T> getArray() {
请注意,使用增强的for循环会更容易:
for (Node<T> node : queue) {
onlyValues.add(node.getValue());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句