Created
June 5, 2012 18:54
-
-
Save billyyarosh/2876945 to your computer and use it in GitHub Desktop.
Simple sort strategy on an object of animals. Group by animal class type.
This file contains hidden or 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
/** | |
* | |
* Run a demo for supplying different strategies to sort a list | |
* of animals. | |
* | |
* @author keaplogik | |
*/ | |
public class RunAnimalStrategyDemo { | |
public static void main(String[] args) { | |
//build the animal list. | |
Animal[] animals = buildAnimalList(); | |
System.out.println("\tGROUP Animals by same class type"); | |
System.out.println("----------------------------------------------"); | |
/** | |
* This is an example of implementing strategy to sort | |
* Animals by their animal class. Order doesn't matter, but we want to | |
* ensure that animals are grouped by their animal class property. | |
*/ | |
Arrays.sort(animals, new Comparator<Animal>() { | |
public int compare(Animal firstAnimal, Animal secondAnimal) { | |
return firstAnimal.getAnimalClass().hashCode() - | |
secondAnimal.getAnimalClass().hashCode(); | |
} | |
}); | |
for (Animal animal : animals) { | |
System.out.println(animal.toString()); | |
} | |
} | |
public static Animal[] buildAnimalList(){ | |
final Animal[] animals = new Animal[10]; | |
animals[0] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, | |
"Dog", true, Color.GRAY); | |
animals[1] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, | |
"Cat", true, Color.YELLOW); | |
animals[2] = new SimpleAnimal(Animal.AnimalClass.AMPHIBIAN, | |
"Frog", true, Color.GREEN); | |
animals[3] = new SimpleAnimal(Animal.AnimalClass.BIRD, | |
"Crow", true, Color.BLACK); | |
animals[4] = new SimpleAnimal(Animal.AnimalClass.BIRD, | |
"Cardinal", true, Color.RED); | |
animals[5] = new SimpleAnimal(Animal.AnimalClass.ARTHROPOD, | |
"Mantis", false, Color.GREEN); | |
animals[6] = new SimpleAnimal(Animal.AnimalClass.ARTHROPOD, | |
"Spider", false, Color.ORANGE); | |
animals[7] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, | |
"Tiger", true, Color.ORANGE); | |
animals[8] = new SimpleAnimal(Animal.AnimalClass.MAMMAL, | |
"Bear", true, Color.BLACK); | |
animals[9] = new SimpleAnimal(Animal.AnimalClass.BIRD, | |
"Owl", true, Color.BLACK); | |
return animals; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment