[英]Creating a Stack Generic ArrayList useing a interface
這是一個關於泛型和實現堆棧(LIFO)的練習題,在現實生活中不用於教育目的。
所有接口方法不能采用不同的參數,必須按照所示方式實現。
接口棧
import java.util.Iterator;
interface Stack<E>{
public boolean push(E x);
public boolean pop();
public E top();
public boolean empty();
public boolean full();
public Iterator<E> iterator();
}
我不知道如何處理iterator
方法或為什么我需要它,因為我的方法都沒有使用它?
我已經完成了下面代碼中的所有其他方法
我的堆棧
import java.util.ArrayList;
import java.util.Iterator;
public class MyStack<E> implements Stack<E>,Iterable<E> {
//Creating a ArrayList which is bound using a int
//in the constructor and size keeps track of the
//amount of elements in the ArrayLIst
private int size;
private ArrayList<E> stack;
public MyStack(int size) {
stack = new ArrayList<E>(size);
size = 0;
}
@Override
public boolean push(E x) {
//Check to make sure the size of the bounded Arraylist
//has not been exceeded, if not add element
if(size == stack.size()) {
stack.add(x);
size++;
return true;
}
return false;
}
@Override
public boolean pop() {
//If the list is not empty remove the last element
if(this.empty()) {
System.out.println("No elements to remove");
return false;
}
stack.remove(stack.size()-1);
size--;
return true;
}
@Override
public E top() {
//If the stack is not empty return the top element without removing it
if (empty()) {
return null;
}
else
return stack.get(stack.size()-1);
}
@Override
public boolean empty() {
return stack.isEmpty();
}
@Override
public boolean full() {
//If size is equal to the size of the stack
//it is deemed full
if(size == stack.size()) {
System.out.println("The stack is full");
return true;
}
return false;
}
@Override
public Iterator iterator() {
// TODO Auto-generated method stub
return null;
}
@Override
public String toString() {
return "MyStack [size=" + size + ", stack=" + stack + "]";
}
}
測試代碼
stack.push(2);
stack.push(4);
stack.push(5);
stack.push(7);
System.out.println(stack.toString());
System.out.println(stack.top());
stack.pop();
stack.empty();
System.out.println(stack.toString());
所有方法似乎都可以正常工作
MyStack [size=4, stack=[2, 4, 5, 7]] 7 MyStack [size=4, stack=[2, 4, 5]]
我唯一的其他困惑是在我的書中,它顯示了添加到頭部的圖表,其中我的 Arraylist 添加到尾部,但將尾部視為頭部,這樣可以嗎?
這有點令人困惑,因為他們還在本章中討論了LinkedList
,這就是這個 daigram 向我表示的東西,而不是ArrayList
。
書中使用的方法
@Override
public Iterator<E> iterator() {
ArrayList<E> tmp = new ArrayList<>();
int ind = stack.size();
while(ind > 0){
tmp.add(stack.get(ind-1));
ind--;
}
System.out.println(tmp.toString());
return tmp.iterator();
}
正如 dan1st 在評論中已經提到的,迭代器用於遍歷/迭代整個堆棧並提供一些函數來與堆棧元素進行交互。
查看Iterator interface的文檔。
通常,接口(您的堆棧)提供的方法不必在您自己的實現中使用,而是為用戶提供一些與您的實現交互的操作。
我唯一的其他困惑是在我的書中,它顯示了添加到頭部的圖表,其中我的 Arraylist 添加到尾部,但將尾部視為頭部,這樣可以嗎?
如果要求是向頭部添加新元素,那就去吧。 它改變了堆棧元素的順序。 這是如何在您的書中使用iterate()
實現的一個很好的提示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.