java practice 利用LinkedList 实现Stack栈接口及实例化对象中toString方法重写

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方法进行重写

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值