How do I sort custom objects alphabetically in an array in Java?

前端 未结 2 611
轻奢々
轻奢々 2020-12-22 00:58

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

2条回答
  •  爱一瞬间的悲伤
    2020-12-22 01:22

    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 inventory = new ArrayList();
    
    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() {
        public int compare(Book result1, Book result2) {
            return result1.getTitle().compareTo(result2.getTitle());
        }
    });
    
    for (int i =0;i

    }

提交回复
热议问题