如何将Int添加到通用Arraylist中,我不确定我是疯了还是不可能

时间:2019-04-14 23:52:55

标签: java generics

我受命将一些代码从使用Int []转换为使用ArrayList。这样做只能编辑以下方法:Stack(int),getStack(),setStack(),stackRead()和stackWrite()。当我这样做时,会遇到许多有关不同类型匹配的错误。

如前所述,我只能编辑Stack(int),getStack(),setStack(),stackRead()和stackWrite()。 在编辑这些代码时,我想出了以下代码:

我的目标是使此代码使用ArrayList,但它会产生许多问题,我尝试更改与泛型相关的所有内容并将其解析为Int,但这会给我带来越界错误。

我已经尝试过使用.toArray将getStack()更改为对象,但仍然给我ArrayIndexOutofBounds

public class Stack<E> {    
     /**
     * This ArrayList stores the values on the Stack, i.e., it is *the stack*.
     */
    private ArrayList<E> mStack;

    /**
    /**
     * Default constructor. Creates a Stack with capacity of 10 ints.
     */
    public Stack() {
        this(10);
    }

    /**
     * This constructor creates a Stack with capacity of pCapacity. It initializes all three of
     * the data members.
     *
     * @param pCapacity - The capacity of the Stack.
     */
    public Stack(int pCapacity) {
        setCapacity(pCapacity);
        setStack(new ArrayList<E>(mCapacity));
        setTop(0);
    }

    private ArrayList<E> getStack() {
        return mStack; 
    }

    public int peek() {
        return (int)stackRead(getTop());
    }



    /**
     * Removes the top element from the Stack.
     *
     * @return The top value.
     */
    public int pop() {
        int topValue = peek();
        stackWrite(getTop(), 0);
        decTop();
        return topValue;
    }

    /**
     * Pushes pValue onto the top of the stack.
     *
     * @param pValue - The value to be pushed onto the top of the stack.
     *
     * @return A reference to the Stack. This permits operations such as:
     * myStack.push(1).push(2).push(3).push(4).
     */    
    public Stack push(int pValue) {
        stackWrite(incTop(), pValue);
        return this;     
    }4

    /**
     * Gets the value at index pIndex from the stack data structure and returns the value.
     *
     * @param pIndex the index into mStack where we are reading a value.
     * @return The value at pIndex.
     */
    private E stackRead(int pIndex) {
        return getStack().get(pIndex);
    }

    /**
     * Puts pValue into the stack data structure at index pIndex.
     *
     * @param pIndex The inex into mStack where we are writing pValue.
     * @param pValue The value to be writtin into mStack.
     *
     * @return pValue.
     */
    private int stackWrite(int pIndex, int pValue) {
        //getStack().set(pIndex,  pValue);

        return  pValue;
    }

}

以某种方式需要编写代码,以便仅编辑允许的方法,同时从1d数组更改为通用ArrayLists

1 个答案:

答案 0 :(得分:1)

您不能在int中存储类似ArrayList的基元。使用Integer类。