0
import java.util.ArrayList;

class Stack {
    private ArrayList stack;
    private int pos;

    Stack() {
        stack = new ArrayList();
        pos = -1;
    }
    int pop() {
        if(pos < 0) {
             System.out.println("Stack underflow.");
             return 0;
        }
        int out = stack.get(pos);
        stack.remove(pos);
        pos--;
        return out;
    }
}

我正在尝试编写一个基本的可变长度堆栈,这是我的代码片段。当我运行它时,我得到一个错误:

Main.java:16: error: incompatible types
   int out = stack.get(pos);
                       ^
required: int
found:    Object

为什么这被作为对象传递?

4

3 回答 3

3

目前,您没有定义ArrayList被调用的泛型类型,stack因此您将从以下位置获得原始Object返回类型ArrayList.get

你需要更换

ArrayList stack;

ArrayList<Integer> stack;

同样地

stack = new ArrayList();

stack = new ArrayList<Integer>(); // new ArrayList<>(); for Java 7

也看看使用java.util.Stack

于 2013-01-04T00:39:25.273 回答
1

stack没有被告知它拥有什么变量类型,所以它求助于泛型Object

ArrayList stack;

应该

ArrayList<Integer> stack;
于 2013-01-04T00:40:23.793 回答
1

stack.get(int)方法返回一个对象。这里的 int 只是索引。如果您想在 index 处获取堆栈的值int并返回 anInteger您需要执行以下操作:

Integer x = stack.get([int index position]);

于 2013-01-04T00:40:37.257 回答