1、
与FIFO(先入先出的)队列类似的一种数据结构是FILO先入后出栈Stack
这里就运用LinkedList这个类实现Stack这个接口
准备 testFile 类 MyStack类接入接口Stack testFile 主要用于泛型
testFile:
package test;
public class testFile{
public String name;
public testFile()
{
}
public testFile(String name)
{
this.name=name;
}
public String toString()
{
return name;
}
}
MyStack:
package test;
import test.testFile;
import java.util.ArrayList;
import java.util.LinkedList;
public class MyStack implements Stack{
LinkedList<testFile> os=new LinkedList<>();
public void push(testFile h) {
os.addLast(h);
}
public testFile pull() {
return os.removeLast();
}
public testFile peek() {
return os.peekLast();
}
public String toString()
{
return os.toString();
}
public static void main(String[] args) {
MyStack sd=new MyStack();
for (int i = 0; i < 5; i++) {
sd.push(new testFile("hero"+i));;
}
System.out.println("以下是入栈的五个对象");
System.out.println(sd);
System.out.println("最后一个对象再取出来:");
System.out.println(sd.peek());
sd.pull();
System.out.println("之后的对象们");
System.out.println(sd);
}
}
Stack:
package test;
import test.testFile;
public interface Stack {
//把对象推入到最后位置
public void push(testFile h);
//把最后一个对象取出来
public testFile pull();
//查看最后一个对象
public testFile peek();
}
细节:
在一个类中导入一个类的时候 在该类中实例化一个对象并对其输入字符串时 需要在被导入的那个类中对其String的toString方法进行重写 返回该值 不然输出会是他的地址。
同上的在对其接口Stack中的方法实现的时候 需要调用public testFile pull() 等方法进行实例化对象 那么为避免输出的是对象地址 需对其toString方法进行重写