开发者

Stack returning Objects instead of Integers

I'm trying to implement a program that involves an array of stacks. Each stack takes in Integer objects, but the problem is when I try to get an Integer object from the stack:

import java.util.*;

public class Blocks
{
    public static void main(String[] args)
    {
        System.out.println();
        Scanner input = new Scanner(System.in);

        Stack[] blocks = new Stack[input.nextInt()];
        for (int i = 0; i < blocks.length; i++) {blocks[i] = new Stack<Integer>();} //initializing main array of stacks of blocks
        for (int i = 0; i < blocks.length; i++) {blocks[i].push(i);} //add first block to each stack
        Stack retainer = new Stack<Integer>(); //used for when moving stacks of blocks instead of one block.

        boolean m; //move or pile
        boolean on; //onto or over

        int fromBlock; //block being moved
        int toBlock; //block where the fromBlock is being moved

        String command = input.next();
        while (!command.equals("quit"))
        {
            m = command.equals("move");
            fromBlock = input.nextInt();
            on = input.next().equals("onto");
            toBlock = input.nextInt();

            if (m) //put back blocks on fromBlock
            {
                if (on) //put back blocks on toBlock
                {
                    int holder = blocks[fromBlock].pop().intValue(); //I get a compiler error here
                    moveOnto(blocks, holder, toBlock);
                }
                else //fromBlock goes on top of stack on toBlock
                {
                }
            }
            else //bring blo开发者_Go百科cks on fromBlock
            {
                if (on) //put back blocks on toBlock
                {
                }
                else //fromBlock goes on top of stack on toBlock
                {
                }
            }

            command = input.next();
        }
    }

    void moveOnto(Stack[] array, int sBlock, int rBlock)
    {

    }
}

The error says that is doesn't recognize .intValue(). Obviously that is a method of Integer, and I found out from that point that it's returning Object objects instead of Integer types. How can I make it return Integer types?


To define an array of generic you need to do this.

@SuppressWarnings("unchecked") // to avoid warnings.
Stack<Integer>[] blocks = new Stack[n];

Then you can write

int holder = blocks[fromBlock].pop();

And yes, it does compile and works just fine.

EDIT: Why the compiler can't let you do

Stack<Integer>[] blocks = new Stack<Integer>[n];

or

Stack<Integer>[] blocks = new Stack<>[n];

to mean the same thing is beyond me.


int holder = blocks[fromBlock].pop().intValue(); //I get a compiler error here

Change that to:

int holder = ((Stack<Integer>blocks[fromBlock]).pop().intValue();

You will get a compiler warning.

Contrary to all the wrong answers here, you can't have an array of a generic type in Java.


(oops - Java doesn't allow arrays of generics) Change your Stack variable declaration to use the generic version of Stack:

Stack<Integer>[] blocks = new Stack<Integer>[input.nextInt()];

Otherwise when you access the non-generic stack's .pop() method it just returns an Object which you would need to cast back to an Integer In order to access Integer methods like intValue():

int holder = ((Integer)blocks[fromBlock].pop()).intValue();

(But you won't need to cast if you fix the declarations.)


Use the Stack Generic version of Stack

i.e.

Stack<Integer>[] blocks = new Stack<Integer>[input.nextInt()];

you have to include the generic parameter on the declared type

i.e.

Stack<Integer[] blocks;


You need to change the type of blocks to Stack<Integer>[].

edit: Code compiles fine. You get a warning, which is there to remind you that a bad array assignment can still occur at runtime, so the compiler cannot guarantee you won't get a ClassCastException at runtime if you write buggy code. However, the posted solution does exactly what the OP wants:

public static void main(String[] args) throws Exception {
    Stack<Integer>[] array = new Stack[] { new Stack(7) };
    Integer result = array[0].pop();
}

class Stack<T> {

    private final T foo;

    public Stack(T foo) {
        this.foo = foo;
    }

    T pop() {
        return foo;
    }
}

ps. to clarify, that warning is there to point out that even though you aren't casting explicitly, you can still get a ClassCastException at runtime, as in the following code:

    public static void main(String[] args) throws Exception {
        Stack<Integer>[] array = new Stack[] { new Stack(7) };

        Stack notAnIntegerStack = new Stack<Object>(new Object());
        array[0] = notAnIntegerStack;

        Integer result = array[0].pop(); // class cast exception at runtime
    }

There are warnings all over this code pointing out the danger, but it will compile. Hope that clears things up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜