How would I sort my inventory
array alphabetically?
This is for a project that I am working on. I tried to use Arrays.sort(inventory);
but
You can`t just sort string attribute of a class by directly putting that class to array.sort. If you use the array list rather than array, then you could use the Collection.sort() to sort the list using field inside the book object.
public static void main(String[] args) {
// book array
ArrayList<Book> inventory = new ArrayList<Book>();
inventory.add (new Book(9781416987116L, "We're going on a bear hunt", "Michael Rosen", 2009, "McElderry", 15.99));
inventory.add (new Book(743200616L, "Simple Abundance", "Sarah Breathnach", 2009, "Scribner", 14.99));
inventory.add(new EBook(75260012L, "David goes to School", "David Shannon", 2010, "Shannon Rock", 11.98, "http://www.tinyurl.qqwert67o9"));
inventory.add (new Book(7423540089L, "No David!", "David Shannon", 2009, "Shannon Rock", 12.99));
inventory.add (new EBook(78137521819L, "The very hungry caterpillar", "Eric Carle", 2005, "Philomel Books", 13.99, "http://www.tinyurl.fguopt8u90"));
Collections.sort(inventory, new Comparator<Book>() {
public int compare(Book result1, Book result2) {
return result1.getTitle().compareTo(result2.getTitle());
}
});
for (int i =0;i<inventory.size();i++){
System.out.println(inventory.get(i).getTitle());
}
}
Arrays.sort() uses the natural ordering of the objects, so that would imply that you need them to implement Comparable
, or you're going to get unreliable sorting behavior.
Simply put, if you want to sort each book by its title, then have it implement Comparable
:
public class Book implements Comparable<Book> {
public int compareTo(Book otherBook) {
return title.compareTo(otherBook.getTitle());
}
}
You'd also want to do the same for the subclass EBook
as well.