gpt4 book ai didi

通用堆栈数组的 JAVA 通配符捕获错误

转载 作者:行者123 更新时间:2023-12-02 00:26:44 25 4
gpt4 key购买 nike

Stack<?>[] stacks = {
new Stack<Bed>(),
new Stack<Bookshelves>(),
new Stack<Chair>(),
new Stack<Desk>(),
new Stack<Table>()
};

这是创建堆栈数组的代码。我将它们放入数组的原因是因为这是作业的要求之一。该程序无需数组即可运行。

此外,堆栈接受泛型,因为我必须创建自己的堆栈(也是作业的要求)。

while(sc.hasNext()){
temp = sc.nextLine().split(" ");
if(temp[0].equals("Bed")){
//beds.push(new Bed(temp[1], temp[2]));
stacks[0].push(new Bed(temp[1], temp[2]));
}else if(temp[0].equals("Table")){
//tables.push(new Table(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), temp[4]));
stacks[4].push(new Table(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), temp[4]));
}else if(temp[0].equals("Desk")){
//desks.push(new Desk(temp[1],temp[2], Integer.parseInt(temp[3]), Integer.parseInt(temp[4])));
stacks[3].push(new Desk(temp[1],temp[2], Integer.parseInt(temp[3]), Integer.parseInt(temp[4])));
}else if(temp[0].equals("Chair")){
//chairs.push(new Chair(temp[1], temp[2]));
stacks[2].push(new Chair(temp[1], temp[2]));
}else if(temp[0].equals("Bookshelves")){
//bookshelves.push(new Bookshelves(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4]), temp[5]));
stacks[1].push(new Bookshelves(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4]), temp[5]));
}else{
color = temp[0];
}
}

此代码从文本文件中获取信息并将对象插入堆栈。

我收到一条错误消息:

push(capture#627 of ?) in Stack<capture#627 of ?> cannot be applied to (Bed)

我创建的所有类都会重复此错误。

注释掉的部分是我之前为每个对象创建单个堆栈时起作用的代码。

将所有内容插入堆栈后,我无法将所有内容放入数组,因为不必要的中间变量会被删除。

最佳答案

正确且类型安全地执行此操作的唯一方法是

a) 将这一切合并为一个Stack<Furniture> (假设所有类都扩展 Furniture )

b) 为每个堆栈保留单独的变量,并完全摆脱数组。

关于通用堆栈数组的 JAVA 通配符捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9876050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com