Java排序:按属性对对象数组进行排序,不允许使用可比较的对象

2022-09-02 12:15:05

我有一个类,Library,其中包含一个 Book 对象数组,我需要根据 Book 的属性(标题或页码)对数组进行排序。问题是不允许将可比类与Book一起使用。你会如何建议我对图书馆中的书籍数组进行排序?写我自己的排序?还是有更简单的方法?如果您需要代码片段,请直接询问!


答案 1

您可以提供 用于比较任何您想要的类型,或者其他方式。ComparatorComparable

对于您使用的数组和集合

Arrays.sort(array, myComparator);
Collections.sort(list, myComparator);

即使是像 TreeSet 这样排序的集合也可以采用自定义比较器

例如:

Collections.sort(books, new Comparator<Book>() {
   public int compare(Book b1, Book b2) {
      return if b1 is greater return +1, if b2 is smaller return -1 otherwise 0
   }
});

答案 2

如果可以使用 ,请为所需的每种类型的排序写一个,例如,升序表示书名,降序表示页码。如果第一个参数大于第二个参数,则 a 的方法必须返回正,如果第一个参数较小,则返回负值;如果它们相等,则返回零。ComparatorscompareComparator

import java.util.Comparator;
import java.util.List;
import java.util.Arrays;

class Book{
    String title;
    int pageNumber;

    public Book(String title, int pageNumber){
        this.title = title;
        this.pageNumber = pageNumber;
    }

    String getTitle(){ return title; }
    int getPageNumber(){ return pageNumber; }

    public String toString(){
        return "(" + title + ", " + pageNumber + " pages)";
    }
}

public class Library{

    // These variables are static because you don't need multiple copies
    // for sorting, as they have no intrinsic state.
    static private Comparator<Book> ascTitle;
    static private Comparator<Book> descPageNumber;

    // We initialize static variables inside a static block.
    static {
        ascTitle = new Comparator<Book>(){
            @Override
            public int compare(Book b1, Book b2){
                return b1.getTitle().compareTo(b2.getTitle());
            }
        };

        descPageNumber = new Comparator<Book>(){
            @Override
            public int compare(Book b1, Book b2){
                // Java 7 has an Integer#compare function
                return Integer.compare(b1.getPageNumber(), b2.getPageNumber());
                // For Java < 7, use 
                // Integer.valueOf(n1).compareTo(n2);
                // DO NOT subtract numbers to make a comparison such as n2 - n1.
                // This can cause a negative overflow if the difference is larger 
                // than Integer.MAX_VALUE (e.g., n1 = 2^31 and n2 = -2^31)
            }
        };
    }

    private Book[] books;
    public Book[] getBooks(){ return books; }

    public void sortAscTitle(){
        Arrays.sort(books, ascTitle);
    }

    public void sortDescPageNumber(){
        Arrays.sort(books, descPageNumber);
    }

    public Library(Book[] books){
        this.books = books;
    }

    public static void main(String[] args){
        Library library = new Library( new Book[]{
            new Book("1984", 123), 
            new Book("I, Robot", 152), 
            new Book("Harry Potter and the Philosopher's Stone", 267),
            new Book("Harry Potter and the Goblet of Fire", 759),
            new Book("The Bible", 1623)
        });

        library.sortAscTitle();
        System.out.println(Arrays.toString(library.getBooks()));

        library.sortDescPageNumber();
        System.out.println(Arrays.toString(library.getBooks()));
    }
}