繁体   English   中英

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

[英]JAVA Wildcard Capture Error with an array of generic stacks

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)为每个堆栈保留单独的变量,并完全摆脱数组。

尝试这个?

((Stack<Bed>)stacks[0]).push(new Bed(temp[1], temp[2]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM