获取StackOverFlowError

时间:2019-07-16 20:02:02

标签: java

我已经创建了类。运行main方法时,在行if(this.compareTo(other) > 0)上出现堆栈溢出错误。不确定我是否对类属使用正确的compareTo方法。 正确的方法是什么?

代码中可能有什么问题?

public class StackMin<T extends Comparable<T>> {
    private static class StackNode<T extends Comparable> implements Comparable {

        private T data;
        private StackNode<T> next;

        public StackNode(T data) {
            this.data = data;
        }

        @Override
        public int compareTo(Object other) {

            if(this.compareTo(other) > 0)
                return 1;
            else if(this.compareTo(other) == 0)
                return 0;
            else
                return -1;
        }

        public String toString() {
            return this.data.toString();
        }
    }

    private StackNode<T> top = null;
    private Stack<StackNode<T>> min = new Stack<StackNode<T>>();


    public void push(T data) {

        StackNode node = new StackNode(data);

        if ( top == null) {
            top = node;
            min.push(node);
        }
        else {
            if ( node.compareTo(top) < 0) {
                min.push(node);
            }
            top.next = top;
            top = node;
        }

    }

    public T pop() throws EmptyStackException {

        if (top == null) {
            throw new EmptyStackException();
        }

        T data = top.data;
        top = top.next;
        min.pop();
        return data;
    }

    public T min() {
        return min.peek().data;

    }

    public boolean empty() {

        return (top == null);

    }

    public static void main(String [] args) {
        StackMin min = new StackMin();
        try {
            min.push(10);
            min.push(9);
            min.push(6);
            min.push(7);
            min.pop();
            System.out.println(min.min());
            min.pop();
            System.out.println(min.min());
            min.pop();
            System.out.println(min.min());
            min.pop();
            System.out.println(min.min());
            min.pop();
            System.out.println(min.min());
        } catch (EmptyStackException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

确定修复它。正在从compareTo调用compareTo

export ENV_VAR=value