java中LinkedList.push的陷阱

结论

使用LinkedList时,尽量使用addLast和addFirst。不要使用push,会和预期不一致。如果要使用push,建议使用Stack。

测试

先看下面一段LinkedList.push代码,

		LinkedList<Integer> deque = new LinkedList<>();
        deque.push(1);
        deque.push(2);
        System.out.println("LinkedList push: " + deque);

想象中的输出应该和Stack一致为[1,2],但实际输出是

LinkedList push: [2, 1]

其他LinkedList方法的测试代码如下,输出和预期是一致的。

        LinkedList<Integer> deque = new LinkedList<>();
        deque.push(1);
        deque.push(2);
        System.out.println("LinkedList push: " + deque);
        //LinkedList push: [2, 1]

        deque.clear();
        deque.addLast(1);
        deque.addLast(2);
        System.out.println("LinkedList addLast: " + deque);
        //LinkedList addLast: [1, 2]

        deque.clear();
        deque.addFirst(1);
        deque.addFirst(2);
        System.out.println("LinkedList addFirst: " + deque);
        //LinkedList addFirst: [2, 1]

        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        System.out.println("stack push: " + stack);
        //stack push: [1, 2]

        stack.clear();
        stack.add(1);
        stack.add(2);
        System.out.println("stack add: " + stack);
        //stack add: [1, 2]
上一篇:C++ std::deque (tcy)


下一篇:C++stack栈