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

これが、スタックの配列を作成するコードです。それらを配列に入れる理由は、それが課題の要件の 1 つだからです。プログラムは配列なしで動作します。

また、独自のスタックを作成する必要があったため、スタックはジェネリックを取り込みます (課題の要件でもあります)。

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)

このエラーは、作成したすべてのクラスで繰り返されます。

コメントアウトされた部分は、各オブジェクトに対して単一のスタックを作成したときに以前に機能したコードです。

すべてをスタックにプッシュした後、すべてを配列に入れることはできません。これは、不要な中間変数に対してポイントが取り出されるためです。

4

2 に答える 2

2

これを適切かつ型安全に行う唯一の方法は、次のいずれかです。

a)これをすべて1つに結合しますStack<Furniture>(クラスがすべて拡張されていると仮定しますFurniture

b)スタックごとに個別の変数を保持し、配列を完全に取り除きます。

于 2012-03-26T16:39:23.897 に答える
1

これを試して?

((Stack<Bed>)stacks[0]).push(new Bed(temp[1], temp[2]));
于 2012-03-26T22:44:04.320 に答える