简体   繁体   中英

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>()
};

That's the code making the array of stacks. The reason I'm putting them in an array is because it's one of the requirements for the Assignment. The program works without the array.

Also, the Stack takes in generics because I had to create my own Stack (also a requirement of the Assignment).

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];
    }
}

This code gets the information from the text file and pushes the Objects into the stack.

I get an Error saying:

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

This Error repeats for all the Classes that I have created.

The parts commented out is the code that worked before when I made a single stack for each Object.

I can't put everything into the array after I have pushed everything into the Stack because points will be taken out for unnecessary intermediate variables.

The only way to do this properly and type-safely is either

a) combine this all into one Stack<Furniture> (assuming the classes all extend Furniture )

b) keep separate variables for each stack, and get rid of the array entirely.

尝试这个?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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