Add a method to CatList with this header public ArrayList getCatsSortedByName() which sorts the inner ArrayList of cats and returns it. Use an anonymous inner class which implements Comparator.
public static void main(String[] args) {
CatList cats = new CatList();
System.out.println("will create the cats");
cats.addCat(new Cat("Frank", "gray"));
cats.addCat(new Cat("Zen", "black"));
cats.addCat(new Cat("Xiongmao", "spotted"));
cats.addCat(new Cat("Little Kit", "calico"));
cats.addCat(new Cat("Ang", "gray"));
System.out.println("Here is the list");
System.out.println(cats);
System.out.println("There are " + cats.howManyCats() + "cats on the list");
//ArrayList<Cat> sortedCats = cats.getCatsSortedByName();
//System.out.println("Here are the sorted cats");
// System.out.println(sortedCats);
//System.out.println("Here is the original list");
//System.out.println(cats);
}
}
If you have any doubts, please give me comment...
import java.util.ArrayList;
class SortByCatName implements Comparator<Cat> {
public int compare(Cat cat1, Cat cat2) {
return cat1.getName().compareTo(cat2.getName());
}
}
class CatList{
ArrayList<Cat> cats;
//rest of code
public ArrayList<Cat> getCatsSortedByName(){
ArrayList<Cat> tempList = cats.clone();
Collections.sort(tempList, new SortByCatName());
return tempList;
}
}
Get Answers For Free
Most questions answered within 1 hours.