java中判断栈是否为空有两个empty方法,stack.empty()和stack.isEmpty()。那么两者有什么区别呢?
还是先看api。empty()方法:
boolean java.util.Stack.empty()
Tests if this stack is empty.
Returns:
true if and only if this stack contains no items; false otherwise.
isEmpty()方法:
boolean java.util.Vector.isEmpty()
Tests if this vector has no components.
Specified by: isEmpty() in List, Overrides: isEmpty() in AbstractCollection
Returns:
true if and only if this vector has no components, that is, its size is zero; false otherwise.
源代码中,empty方法是Stack类中
public boolean empty() {
return size() == 0;
}
而size()是在Vector类中实现的,如下
public synchronized int size() {
return elementCount;
}
isEmpty()方法在Vector类中实现,代码如下:
public synchronized boolean isEmpty() {
return elementCount == 0;
}
总结:Stack是继承自Vector,所以Stack类型的对象可以访问Vector对象中的方法,那么问题来了,当Stack和Vector中有完成相同功能的方法时,应该调用Stack中的还是Vector中的呢?