判断Stack为空的方法之empty()与isEmpty()

今天写算法时,无意间看到了判断栈是否为空的两个方法,之前一直用isEmpty(),从未用过empty(),却不曾想两者均可判断一个栈是否为空,所以深入源码探究了一番:
java.util.Vector:

/**
     * Tests if this vector has no components.
     *
     * @return  {@code true} if and only if this vector has
     *          no components, that is, its size is zero;
     *          {@code false} otherwise.
     */
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }
	 /**
     * Returns the number of components in this vector.
     *
     * @return  the number of components in this vector
     */
    public synchronized int size() {
        return elementCount;
    }

java.util.Stack 类中:

/**
     * Tests if this stack is empty.
     *
     * @return  <code>true</code> if and only if this stack contains
     *          no items; <code>false</code> otherwise.
     */
    public boolean empty() {
        return size() == 0;
    }

class Stack<E> extends Vector<E>
java.util.Stack类中,size()方法是使用的java.util.Vector的size()方法,那么从源码上看,empty()和isEmpty()两者无本质区别。

当判断一个栈是否为空时,使用stack.empty()与stack.isEmpty()均可,只是两个方法存在的类不同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值