用LinkedList list实现栈的功能
package homework;
public class Dog extends Pet {
String strain = "dogxx";
int love=80;
public Dog() {
}
public String getStrain() {
return strain;
}
public void setStrain(String strain) {
this.strain = strain;
}
public int getLove() {
return love;
}
public void setLove(int love) {
this.love = love;
}
public Dog(String name,String strain,int health) {
super(name,health);
this.strain = strain;
}
public void print() {
super.print();
System.out.println(" "+strain);
}
@Override
//自定义规则去比较 equals
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj instanceof Dog) {
Dog dog = (Dog)obj;
//狗的品种和名称 相等
if(dog.strain.equals(this.strain) && dog.name.equals(this.name)) {
return true;
}
}
return false;
}
@Override
public String toString() {
String str = this.name+"\t"+this.strain+"\t"+this.health;
return str;
}
public void toHos() {
this.health += 50;
System.out.println("狗打针,吃药!");
}
@Override
public void eat() {
if(this.health+3 > 100) {
System.out.println("不能再吃了!");
} else {
System.out.println("狗在吃东西");
this.health += 3;
}
}
public void jiao() {
System.out.println("狗狗叫!");
}
}
//父类
package homework;
public abstract class Pet {
String name="无名";
int health=100;
int love=100;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getLove() {
return love;
}
public void setLove(int love) {
this.love = love;
}
public Pet() {}
public Pet(String name,int health) {
this.name = name;
this.health = health;
}
public void print() {
System.out.println(name+" "+health+" "+love);
}
public void toHos() {
this.health += 50;
}
public abstract void eat();
public abstract void jiao();
}
//栈
package homework;
import java.util.LinkedList;
//10 dog
public class Stack {
LinkedList list = new LinkedList();
//入栈
public void push(Pet pet) {
list.addFirst(pet);
}
//出栈 顺便把数据清除掉
public Pet pop() {
return (Pet) list.removeFirst();
}
//判断是否满了
public boolean isFull() {
if(list.size() >= 10) {
return true;
} else {
return false;
}
}
//判断栈是否空了
public boolean empty() {
if(list.size()==0) {
return true;
} else {
return false;
}
}
}
//测试文件
package homework;
public class Test {
public static void main(String[] args) {
Stack stack = new Stack();
for (int i = 0; i < 100; i++) {
Dog dog = new Dog();
dog.setName("神犬"+(i+1)+"号");
dog.setStrain("神犬");
if(!stack.isFull()) {
stack.push(dog);
System.out.println(dog.getName());
} else {
break;
}
}
do {
Pet pet = stack.pop();
System.out.println(pet.getName());
} while(!stack.empty());
if(stack.empty()) {
System.out.println("栈清空了!");
} else {
System.out.println("栈还没空!");
}
}
}