-
-
Save jason51122/2936de75e6f1dd06d1b7 to your computer and use it in GitHub Desktop.
3.7 An animal shelter holds only dogs and cats, and operates on a strictly "first in, first out" basis. People must adOPT either the "oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific anim…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class Animal { | |
private int index; | |
private String name; | |
public Animal(String name) { | |
this.name = name; | |
} | |
public int getIndex() { | |
return index; | |
} | |
public void setIndex(int index) { | |
this.index = index; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
} | |
public class Dog extends Animal { | |
public Dog(String name) { | |
super(name); | |
} | |
} | |
public class Cat extends Animal { | |
public Cat(String name) { | |
super(name); | |
} | |
} | |
import java.util.LinkedList; | |
public class AnimalQueue { | |
private LinkedList<Dog> dogQueue; | |
private LinkedList<Cat> catQueue; | |
private int index; | |
public AnimalQueue() { | |
dogQueue = new LinkedList<Dog>(); | |
catQueue = new LinkedList<Cat>(); | |
index = 0; | |
} | |
public void enqueue(Animal animal) { | |
animal.setIndex(index); | |
index++; | |
if (animal instanceof Dog) { | |
// Convert Animal to specific type. | |
dogQueue.add((Dog) animal); | |
} | |
else { | |
catQueue.add((Cat) animal); | |
} | |
} | |
public Animal dequeueAny() throws Exception { | |
if (dogQueue.isEmpty() && catQueue.isEmpty()) { | |
throw new Exception("Queue is empty."); | |
} | |
if (dogQueue.isEmpty()) { | |
return catQueue.remove(); | |
} | |
else if (catQueue.isEmpty()) { | |
return dogQueue.remove(); | |
} | |
else { | |
Dog dog = dogQueue.getFirst(); | |
Cat cat = catQueue.getFirst(); | |
if (dog.getIndex() < cat.getIndex()) { | |
return dog; | |
} | |
else { | |
return cat; | |
} | |
} | |
} | |
public Dog dequeueDog() throws Exception { | |
if (dogQueue.isEmpty()) { | |
throw new Exception("Dog queue is empty."); | |
} | |
return dogQueue.remove(); | |
} | |
public Cat dequeueCat() throws Exception { | |
if (catQueue.isEmpty()) { | |
throw new Exception("Cat queue is empty."); | |
} | |
return catQueue.remove(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment