英文:
Why does my generic linkedlist get this error?
问题
我不明白为什么这段代码不起作用,我相信我正确地使用了泛型,但是这个方法显然未定义?node和linkedlist类是完全通用的,我正在创建不同类型的节点(例如semicircle),它们共享相同的抽象超类PlanarShape,并尝试将它们添加到已实例化的相应类型的链表中。
主类的相关部分
LinkedList<PlanarShape> plygns = new LinkedList<PlanarShape>();
Point p0 = new Point(Double.parseDouble(sc.next()), Double.parseDouble(sc.next()));
Point p1 = new Point(Double.parseDouble(sc.next()), Double.parseDouble(sc.next()));
SemiCircle smc = new SemiCircle(p0, p1);
plygns.prepend(new Node<SemiCircle>(smc));
prepend 正在报错,错误信息为 prepend(Node
Linkedlist 的 prepend 方法
public void prepend(Node<T> n) //add to head
{
//在修复错误之前为空
}
英文:
I can't see why this code is not working, I believe I am using generics correctly but the method is apparently not defined? node and linkedlist classes are completely generic and I am creating a node of different types (eg semicircle) that share the same abstract superclass PlanarShape and trying to add them to an instantiated linklist of that type.
Relevant part of main class
LinkedList<PlanarShape> plygns = new LinkedList<PlanarShape>();
Point p0 = new Point(Double.parseDouble(sc.next()), Double.parseDouble(sc.next()));
Point p1 = new Point(Double.parseDouble(sc.next()), Double.parseDouble(sc.next()));
SemiCircle smc = new SemiCircle(p0, p1);
plygns.prepend(new Node<SemiCircle>(smc));
prepend is getting the error prepend(Node<SemiCircle>) is undefined for the type Linkedlist<Planarshape>
Linkedlist method prepend
public void prepend(Node<T> n) //add to head
{
//Empty until error fixed
}
答案1
得分: 0
你有一个PlanarShapes列表,正在尝试"prepend"一个类型为SemiCircle的Node。根据你编写的prepend方式,它将仅接受类型为PlanarShape的Nodes。
假设SemiCircle是PlanarShape的子类型,你需要更改prepend以允许T的子类型带有通配符:
public void prepend(Node<? extends T> n) {
...
}
英文:
You have a list of PlanarShapes and you're trying to "prepend" a Node with type SemiCircle. With the way you have written prepend, it will accept Nodes with type PlanarShape
only.
Assuming SemiCircle
is a subtype of PlanarShape
, you'll need to change prepend to allow subtypes of T with a "wildcard":
public void prepend(Node<? extends T> n) {
...
}
专注分享java语言的经验与见解,让所有开发者获益!
评论