簡體   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