Created
July 12, 2014 23:01
-
-
Save iwilbert/896f3f2b5b67a0ee3340 to your computer and use it in GitHub Desktop.
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 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