今天写算法时,无意间看到了判断栈是否为空的两个方法,之前一直用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()均可,只是两个方法存在的类不同。