【題目】
寵物、狗和貓的類如下: 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");
}
}
實(shí)現(xiàn)一種狗貓隊(duì)列的結(jié)構(gòu),要求如下: 用戶可以調(diào)用add方法將cat類或dog類的實(shí)例放入隊(duì)列中; 用戶可以調(diào)用pollAll方法,將隊(duì)列中所有的實(shí)例按照進(jìn)隊(duì)列的先后順序依次彈出; 用戶可以調(diào)用pollDog方法,將隊(duì)列中dog類的實(shí)例按照進(jìn)隊(duì)列的先后順序依次彈出; 用戶可以調(diào)用pollCat方法,將隊(duì)列中cat類的實(shí)例按照進(jìn)隊(duì)列的先后順序依次彈出; 用戶可以調(diào)用isEmpty方法,檢查隊(duì)列中是否還有dog或cat的實(shí)例; 用戶可以調(diào)用isDogEmpty方法,檢查隊(duì)列中是否有dog類的實(shí)例; 用戶可以調(diào)用isCatEmpty方法,檢查隊(duì)列中是否有cat類的實(shí)例。
【要求】
要求即題目。
【解答】
見源碼!
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();
}
}