当前位置: 代码迷 >> java >> 在Java中实现ArrayList并获取单个值
  详细解决方案

在Java中实现ArrayList并获取单个值

热度:94   发布时间:2023-07-17 20:59:51.0

我一直在尝试找出过去几个小时内如何获取数组列表的值,而我似乎找不到任何真正有用的答案。 我正在尝试获得以下结果:

STACK TESTING

4

8

8

9

The size of the stack is: 3

The stack contains:

9

7

3

现在我可以进行堆栈测试,然后依次进行4、8、8、9,但是我无法获取堆栈的实际大小以打印其中包含的项目数,然后打印列表中的每个项目,例如以上。 每当我尝试在toString方法中使用某些东西时,它都会给我一个类似于此错误“无法在数组类型T []上调用size()。如果我使用stack.length输出100,但这不是我所需要的。” m主要处理isEmpty(),size()和toString()

这是我的代码:

import java.util.Arrays;


public class Murray_A05Q1 {
    public static void main(String[] args) {

        ArrayStack<Integer> stack = new ArrayStack<Integer>();


        System.out.println("STACK TESTING");

        stack.push(3); // <----- bottom
        stack.push(7);
        stack.push(4); // <----- top 
        System.out.println(stack.peek()); // <--- peeking top so 4
        stack.pop(); // <----- popping off top so its popping off 4
        stack.push(9); 
        stack.push(8); // <---- new final top 8,9,7,3
        System.out.println(stack.peek());  // <------ peeking at 8     
        System.out.println(stack.pop()); // <------ popping off 8 to leave 9,7,3
        System.out.println(stack.peek()); // <------ peeking now at 9 

        int value = stack.size();

        System.out.println("The size of the stack is: " + stack.size());
        System.out.println("The stack contains:\n" + stack.toString());        

    } // End of main method header

    public static class ArrayStack<T> implements StackADT<T>
    {
        private final static int DEFAULT_CAPACITY = 100;

        private int top;  
        private T[] stack;

        /**
         * Creates an empty stack using the default capacity.
         */
        public ArrayStack()
        {
            this(DEFAULT_CAPACITY);
        }

        /**
         * Creates an empty stack using the specified capacity.
         * @param initialCapacity the initial size of the array 
         */
        @SuppressWarnings("unchecked") //see p505.
        public ArrayStack(int initialCapacity)
        {
            top = 0;
            stack = (T[])(new Object[initialCapacity]);
        }

        /**
         * Adds the specified element to the top of this stack, expanding
         * the capacity of the array if necessary.
         * @param element generic element to be pushed onto stack
         */
        public void push(T element)
        {
            if (size() == stack.length) 
                expandCapacity();

            stack[top] = element;
            top++;
        }

        /**
         * Creates a new array to store the contents of this stack with
         * twice the capacity of the old one.
         */
        private void expandCapacity()
        {
            stack = Arrays.copyOf(stack, stack.length * 2);   
        }

        /**
         * Removes the element at the top of this stack and returns a
         * reference to it. 
         * @return element removed from top of stack
         * @throws EmptyCollectionException if stack is empty 
         */
        public T pop() throws EmptyCollectionException
        {
            if (isEmpty())
                throw new EmptyCollectionException("stack");

            top--;
            T result = stack[top];
            stack[top] = null; 

            return result;
        }

        /**
         * Returns a reference to the element at the top of this stack.
         * The element is not removed from the stack. 
         * @return element on top of stack
         * @throws EmptyCollectionException if stack is empty
         */
        public T peek() throws EmptyCollectionException
        {
            if (isEmpty())
                throw new EmptyCollectionException("stack");

            return stack[top-1];
        }

        /**
         * Returns true if this stack is empty and false otherwise. 
         * @return true if this stack is empty
         */
   //*****************************
   // First one to be implemented
   //*****************************
        public boolean isEmpty()
        {

            return (stack == null);
        }

        /**
         * Returns the number of elements in this stack.
         * @param stack2 
         * @return the number of elements in the stack
         */
        public int size()
        {

            return 0; // have this set to 0 temporary since I'm getting the error

        }


        /**
         * Returns a string representation of this stack. The string has the
         * form of each element printed on its own line, with the top most
         * element displayed first, and the bottom most element displayed last.
         * If the list is empty, returns the word "empty".
         * @return a string representation of the stack
         */


        public String toString()
        {

           return stack.size;

        }


        }  
}

为此,我还有另外三个文件:

文件1

public class LinearNode<T>
{
    private LinearNode<T> next;
    private T element;

    /**
     * Creates an empty node.
     */
    public LinearNode()
    {
        next = null;
        element = null;
    }

    /**
     * Creates a node storing the specified element.
     * @param elem element to be stored
     */
    public LinearNode(T elem)
    {
        next = null;
        element = elem;
    }

    /**
     * Returns the node that follows this one.
     * @return reference to next node
     */
    public LinearNode<T> getNext()
    {
        return next;
    }

    /**
     * Sets the node that follows this one.
     * @param node node to follow this one
     */
    public void setNext(LinearNode<T> node)
    {
        next = node;
    }

    /**
     * Returns the element stored in this node.
     * @return element stored at the node
     */
    public T getElement()
    {
        return element;
    }

    /**
     * Sets the element stored in this node.
     * @param elem element to be stored at this node
     */
    public void setElement(T elem)
    {
        element = elem;
    }
}

文件2

public interface StackADT<T>
{
    /**  
     * Adds the specified element to the top of this stack. 
     * @param element element to be pushed onto the stack
     */
    public void push(T element);

    /**  
     * Removes and returns the top element from this stack. 
     * @return the element removed from the stack
     */
    public T pop();

    /**  
     * Returns without removing the top element of this stack. 
     * @return the element on top of the stack
     */
    public T peek();

    /**  
     * Returns true if this stack contains no elements. 
     * @return true if the stack is empty
     */
    public boolean isEmpty();

    /** 
     * Returns the number of elements in this stack. 
     * @return the number of elements in the stack
     */
    public int size();

    /**  
     * Returns a string representation of this stack. 
     * @return a string representation of the stack
     */
    public String toString();
}

最后,文件#3

public class EmptyCollectionException extends RuntimeException {

    /**
     * Sets up this exception with an appropriate message.
     * @param collection the name of the collection
     */
    public EmptyCollectionException(String collection)
    {
        super("The " + collection + " is empty.");
    }

}

谁能向我解释为什么我无法在toString(),size()和isEmpty()方法中做任何事情而没有得到指向T []的错误?

万分感谢!!

你可能想要这样的东西

        public boolean isEmpty()
        {

            return (top == 0);
        }

        /**
         * Returns the number of elements in this stack.
         * @param stack2 
         * @return the number of elements in the stack
         */
        public int size()
        {

            return top; // have this set to 0 temporary since I'm getting the error

        }


        /**
         * Returns a string representation of this stack. The string has the
         * form of each element printed on its own line, with the top most
         * element displayed first, and the bottom most element displayed last.
         * If the list is empty, returns the word "empty".
         * @return a string representation of the stack
         */


        public String toString()
        {
           int top1 = top -1;
           String finishedString = "";
           for(int i = top1;i >= 0;i--)
           {
            finishedString += stack[i].toString() + "\n";
           }
           return finishedString;

        }
  相关解决方案