1.Create class Dog with instance variable breed and height. Create 5 instances of Dog and add it to the Treeset dogSet. The Treeset should be in sorted order of height using a Comparator interface. Iterate through the Treeset using a for-each loop and print the height and breed of each Dog.
import java.util.*;
class Dog {
String breed;
int height;
Dog(String breed,int height){
this.breed=breed;
this.height=height;
}
public void setBreed(String breed){
this.breed = breed;
}
public String getBreed(){
return breed;
}
public void setHeight(int height) {
this.height = height;
}
public int getHeight(){
return height;
}
}
class HeightComparator implements Comparator{
public int compare(Object o1, Object o2){
int h1 = ((Dog)o1).getHeight();
int h2 = ((Dog)o2).getHeight();
return h1-h2;
}
}
public class TreeSetEx{
public static void main(String[] args){
TreeSet<Dog> dogset=new TreeSet<Dog>(new HeightComparator());
dogset.add(new Dog("German Shepherd",25));
dogset.add(new Dog("Pomeranian",10));
dogset.add(new Dog("Skye Terrier",9));
dogset.add(new Dog("Boxer",24));
dogset.add(new Dog("Mastiff",29));
System.out.println("Sorting according to the Height: ");
for(Dog data: dogset){
System.out.println(data.getBreed()+"\t "+data.getHeight());
}
}
}