【题目】
宠物、狗和猫的类如下: 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");
}
}
实现一种狗猫队列的结构,要求如下: 用户可以调用add方法将cat类或dog类的实例放入队列中; 用户可以调用pollAll方法,将队列中所有的实例按照进队列的先后顺序依次弹出; 用户可以调用pollDog方法,将队列中dog类的实例按照进队列的先后顺序依次弹出; 用户可以调用pollCat方法,将队列中cat类的实例按照进队列的先后顺序依次弹出; 用户可以调用isEmpty方法,检查队列中是否还有dog或cat的实例; 用户可以调用isDogEmpty方法,检查队列中是否有dog类的实例; 用户可以调用isCatEmpty方法,检查队列中是否有cat类的实例。
【要求】
要求即题目。
【解答】
见源码!
package pers.mao.stackAndQueue.demo_4;
/**
* @author Mao Qingbo
* @date 2020-10-03
*/
public class PetEnterQueue {
private Pet pet;
private long count;
public PetEnterQueue(Pet pet,long count){
this.pet = pet;
this.count = count;
}
public Pet getPet() {
return this.pet;
}
public long getCount() {
return this.count;
}
public String getPetEntranceType(){
return this.pet.getPetType();
}
}
package pers.mao.stackAndQueue.demo_4;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author Mao Qingbo
* @date 2020-10-03
*/
public class DogCatQueue {
private Queue<PetEnterQueue> DogQ;
private Queue<PetEnterQueue> CatQ;
private long count;
public DogCatQueue() {
this.DogQ = new LinkedList<PetEnterQueue>();
this.CatQ = new LinkedList<PetEnterQueue>();
this.count = 0;
}
public void add(Pet pet){
if(pet.getPetType().equals("dog")){
this.DogQ.add(new PetEnterQueue(pet,this.count++));
}
else if(pet.getPetType().equals("cat")) {
this.CatQ.add(new PetEnterQueue(pet, this.count++));
}
else{
throw new RuntimeException("error,not dog or cat");
}
}
public Pet pollAll(){
if(!DogQ.isEmpty()&&!CatQ.isEmpty()){
if(DogQ.peek().getCount()<CatQ.peek().getCount()){
return this.DogQ.poll().getPet();
}
else{
return this.CatQ.poll().getPet();
}
}
else if(!DogQ.isEmpty()){
return this.DogQ.poll().getPet();
}
else if(!CatQ.isEmpty()){
return this.CatQ.poll().getPet();
}
else{
throw new RuntimeException("error,Queue is empty!");
}
}
public Pet pollDog(){
if(!this.isDogEmpty()){
return this.DogQ.poll().getPet();
}
else
throw new RuntimeException("no dog!");
}
public Pet pollCat(){
if(!this.isCatEmpty()){
return this.CatQ.poll().getPet();
}
else
throw new RuntimeException("no cat!");
}
public boolean isEmpty(){
return this.DogQ.isEmpty()&&this.CatQ.isEmpty();
}
public boolean isDogEmpty(){
return this.DogQ.isEmpty();
}
public boolean isCatEmpty(){
return this.CatQ.isEmpty();
}
}