class Pet { private String type; public Pet(String type) { this.type = type; } public String getType() { return this.type; } } class Cat extends Pet { public Cat() { super("Cat"); } } class Dog extends Pet { public Dog() { super("Dog"); } } class PetEle { private Pet pet; private Integer rank; PetEle(Pet pet, Integer rank) { this.pet = pet; this.rank = rank; } @Override public String toString() { return pet.toString() + ":" + rank; } public Pet getPet() { return this.pet; } public Integer getRank() { return this.rank; } } class PetQueue { private Integer rank; private Queue<PetEle> catQueue; private Queue<PetEle> dogQueue; public PetQueue() { this.rank = 0; this.catQueue = new LinkedList<>(); this.dogQueue = new LinkedList<>(); } public void add(Pet pet) { if (pet instanceof Cat) { catQueue.offer(new PetEle(pet, rank ++)); } if (pet instanceof Dog) { dogQueue.offer(new PetEle(pet, rank ++)); } } public void pollAll() { while (! catQueue.isEmpty() && ! dogQueue.isEmpty()) { PetEle catEle = catQueue.peek(); PetEle dogEle = dogQueue.peek(); if (catEle.getRank() < dogEle.getRank()) { catQueue.poll(); System.out.println(catEle.getPet()); } else { dogQueue.poll(); System.out.println(dogEle.getPet()); } } while (! catQueue.isEmpty()) { PetEle catEle = catQueue.poll(); System.out.println(catEle.getPet()); } while (! dogQueue.isEmpty()) { PetEle dogEle = dogQueue.poll(); System.out.println(dogEle.getPet()); } } public void pollDog() { if (! dogQueue.isEmpty()) { PetEle dogEle = dogQueue.poll(); System.out.println(dogEle.getPet()); } } public void pollCat() { if (! catQueue.isEmpty()) { PetEle catEle = catQueue.poll(); System.out.println(catEle.getPet()); } } public boolean isEmpty() { return catQueue.isEmpty() && dogQueue.isEmpty(); } public boolean isDogEmpty() { return dogQueue.isEmpty(); } public boolean isCatEmpty() { return catQueue.isEmpty(); } }
转载于:https://blog.51cto.com/tianyiya/2311942