Как добавить Int в общий Arraylist, я не уверен, что я сумасшедший или это невозможно - PullRequest
0 голосов
/ 15 апреля 2019

Мне было поручено преобразовать некоторый код из использования Int [] в использование ArrayList. При этом мне разрешено редактировать только эти методы: Stack (int), getStack (), setStack (), stackRead () и stackWrite (). Когда я делаю это, я получаю массу ошибок, связанных с различными типами совпадений.

Как указывалось ранее, я могу редактировать только Stack (int), getStack (), setStack (), stackRead () и stackWrite (). При редактировании я пришел с кодом ниже:

Моя цель - заставить этот код использовать ArrayList, но он создает много проблем, я пытался изменить все, что имеет отношение к универсальному, и анализировать на Int, но это выдает мои ошибки за пределами допустимого.

Я уже пытался изменить getStack () на объект с помощью .toArray, и он все еще дает мне 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 Arrays к универсальным ArrayLists

1 Ответ

1 голос
/ 15 апреля 2019

Вы не можете хранить примитивы типа int в ArrayList.Используйте класс Integer.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...