2012-03-26 4 views
0
Stack<?>[] stacks = { 
    new Stack<Bed>(), 
    new Stack<Bookshelves>(), 
    new Stack<Chair>(), 
    new Stack<Desk>(), 
    new Stack<Table>() 
}; 

これはスタックの配列を作るコードです。私がそれらを配列に入れているのは、それが割り当ての要件の1つなのでです。プログラムは配列なしで動作します。ジェネリックスタックの配列を持つJAVAワイルドカードキャプチャエラー

また、スタックはジェネリックスを取り入れます。なぜなら、独自のスタックを作成する必要があったからです(割り当ての要件もあります)。

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) 

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

コメントアウトされた部分は、オブジェクトごとに1つのスタックを作成したときに動作していたコードです。

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

答えて

2

これを行うための唯一の方法は、適切に型安全であるいずれか

A)オールインワンStack<Furniture>にこれを組み合わせる())

BをすべてFurnitureを拡張するクラスを仮定して、各スタックのための別の変数を保持し、配列全体を取り除くことができます。

+0

これは、動作しませんでした。また、割り当てに 'b'オプションを使用することはできません。 – prunes4u

+0

私はこれが、これを適切に行うか、安全にタイプする方法であると言ったときにそれを意味しました。代わりに型安全性を失い、安全でない生のキャストを開始することです: '(Stack)stacks [0] .push'は' Object'をとります。 Ewwwwwwwwww。 –

+2

ええ、私はなぜ割り当てがこれを必要とするのか分かりません。貧しいデザインを教えているようです。 –

1

お試しください。

((Stack<Bed>)stacks[0]).push(new Bed(temp[1], temp[2])); 
関連する問題