棧是一種先進後出的數據結構,Stack 是 Vector 的子類,但 Stack 並不使用 Vector 的方法。
在進行棧操作的過程中,如果已經棧已經沒有數據了,那麼無法繼續出棧。
import java.util.*;
class Book{
private String title;
private int price;
public Book(String title, int price){
this.title = title;
this.price = price;
}
@Override
public String toString() {
return this.title + " " + this.price;
}
@Override
public int hashCode() {
return Objects.hash(title, price);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Book other = (Book) obj;
return Objects.equals(this.title, other.title)
&& Objects.equals(this.price, other.price);
}
}
public class Main {
public static void main(String[] args) throws Exception{
// 設置了泛型,從而保證集合中所有的數據類型都一致
Book bookA = new Book("java",100);
Book bookB = new Book("c",89);
Book bookC = new Book("c++",100);
Book bookD = new Book("python",100);
Stack <Book> stack = new Stack <Book>();
stack.push(bookA);
stack.push(bookB);
stack.push(bookC);
stack.push(bookD);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}