Skip to content

Instantly share code, notes, and snippets.

@iwilbert
Created July 12, 2014 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwilbert/896f3f2b5b67a0ee3340 to your computer and use it in GitHub Desktop.
Save iwilbert/896f3f2b5b67a0ee3340 to your computer and use it in GitHub Desktop.
public class AnimalSehelter {
private int id;
private Queue<Cat> Cats;
private Queue<Dog> Dogs;
public AnimalSehelter() {
this.id = 1;
this.Cats = new LinkedList<Cat>();
this.Dogs = new LinkedList<Dog>();
}
public void enqueue(Animal animal) {
animal.setID(this.id++);
if (animal instanceof Cat) {
this.Cats.add((Cat) animal);
}
if (animal instanceof Dog) {
this.Dogs.add((Dog) animal);
}
}
public Animal dequeueAny() {
if (Cats.isEmpty())
return dequeueDog();
if (Dogs.isEmpty())
return dequeueCat();
if (Cats.peek().id < Dogs.peek().id)
return dequeueCat();
else
return dequeueDog();
}
public Cat dequeueCat() {
if (Cats.isEmpty())
throw new NoSuchElementException("queue underflow!");
return Cats.poll();
}
public Dog dequeueDog() {
if (Dogs.isEmpty())
throw new NoSuchElementException("queue underflow!");
return Dogs.poll();
}
}
class Animal {
int id;
public void setID(int id) {
this.id = id;
}
}
class Cat extends Animal {
}
class Dog extends Animal {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment