给定下面的宠物类,要求实现下面的要求:
public class Pet{
private String type;
public Pet(String type){
this.type = type;
}
public String getPetType(){
return this.type;
}
}
public class Dog extends Pet{
public Dog(){
super("dog");
}
}
public class Cat extends Pet{
public Cat(){
super("cat");
}
}
import java.util.LinkedList;
import java.util.Queue;
public class DogAndCatQueue {
//原始的pet类
public static class Pet{
private String type;
public Pet(String type){
this.type = type;
}
public String getPetType(){
return this.type;
}
}
//原始的dog类
public static class Dog extends Pet{
public Dog(){
super("dog");
}
}
//原始的cat类
public static class Cat extends Pet{
public Cat(){
super("cat");
}
}
//新建一个宠物类
public static class SuperPet{
//装一个宠物和一个计数表示进队时间
private Pet pet;
private long count;
public SuperPet(Pet pet,long count){
this.pet = pet;
this.count = count;
}
public Pet getPet(){
return this.pet;
}
public long getCount(){
return this.count;
}
public String getPetType(){
return this.pet.getPetType();
}
}
//猫狗队列
public static class DogCatQueue{
//创建两个队列表示猫队列和狗队列
private Queue<SuperPet> dogQueue;
private Queue<SuperPet> catQueue;
private long count;
public DogCatQueue(){
this.dogQueue = new LinkedList<SuperPet>();
this.catQueue = new LinkedList<SuperPet>();
this.count = 0;
}
//猫狗进队列
public void add(Pet pet){
if(pet.getPetType().equals("dog")){
this.dogQueue.add(new SuperPet(pet,this.count++));
} else if(pet.getPetType().equals("cat")){
this.catQueue.add(new SuperPet(pet,this.count++));
} else {
throw new RuntimeException("error,not dog or cat");
}
}
//获得所有宠物里边的最早的宠物
public Pet pollAll(){
if(!this.dogQueue.isEmpty() && !this.catQueue.isEmpty()){
if(this.dogQueue.peek().getCount() < this.catQueue.peek().getCount()){
return this.dogQueue.poll().getPet();
} else {
return this.catQueue.poll().getPet();
}
} else if(!this.dogQueue.isEmpty()){
return this.dogQueue.poll().getPet();
} else if(!this.catQueue.isEmpty()){
return this.catQueue.poll().getPet();
} else {
throw new RuntimeException("error,queue is empty");
}
}
//取得最早的猫
public Cat pollCat(){
if(!this.catQueue.isEmpty()){
return (Cat) this.catQueue.poll().getPet();
} else {
throw new RuntimeException("cat queue is empty");
}
}
//取得最早的狗
public Dog pollDog(){
if(!this.dogQueue.isEmpty()){
return (Dog) this.dogQueue.poll().getPet();
} else {
throw new RuntimeException("dog queue is empty");
}
}
//判断队列是否为空
public boolean isEmpte(){
return this.dogQueue.isEmpty() && this.catQueue.isEmpty();
}
//判断队列中是否有狗
public boolean dogIsEmpty(){
return this.dogQueue.isEmpty();
}
//判断队列中是否有猫
public boolean catIsEmpty(){
return this.catQueue.isEmpty();
}
}
}