Sorting Arrays of Objects in Java
Problem:
You have an array of objects that do not contain strings but instead have object references. Each object reference provides information about name, ID, author, and publisher through a toString method. The task is to sort this array by the name field. However, you are uncertain how to extract the name from each object and use it as the sorting criteria.
Solution:
To extract the name from each object and sort by this field, you can use the following approach:
List<Book> books = new ArrayList<Book>(); Collections.sort(books, new Comparator<Book>() { @Override public int compare(Book o1, Book o2) { return o1.getName().compareTo(o2.getName()); } });
In this example:
The above is the detailed content of How to Sort an Array of Objects by Name in Java?. For more information, please follow other related articles on the PHP Chinese website!