如何在Java中对对象数组进行排序?

我的数组不包含任何字符串。但是它包含对象引用。每个对象引用都通过toString方法返回名称,id,作者和发布者。

public String toString() {

return (name + "\n" + id + "\n" + author + "\n" + publisher + "\n");

}

现在,我需要按名称对对象数组进行排序。我知道如何排序,但是我不知道如何从对象中提取名称并对它们进行排序。

回答:

你有两种方法可以使用Arrays实用程序类

实现一个Comparator并将数组与比较器一起传递给sort方法,该方法将其作为第二个参数。

在对象所属的类中实现Comparable接口,并将数组传递给仅采用一个参数的sort方法。

class Book implements Comparable<Book> {

public String name, id, author, publisher;

public Book(String name, String id, String author, String publisher) {

this.name = name;

this.id = id;

this.author = author;

this.publisher = publisher;

}

public String toString() {

return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");

}

@Override

public int compareTo(Book o) {

// usually toString should not be used,

// instead one of the attributes or more in a comparator chain

return toString().compareTo(o.toString());

}

}

@Test

public void sortBooks() {

Book[] books = {

new Book("foo", "1", "author1", "pub1"),

new Book("bar", "2", "author2", "pub2")

};

// 1. sort using Comparable

Arrays.sort(books);

System.out.println(Arrays.asList(books));

// 2. sort using comparator: sort by id

Arrays.sort(books, new Comparator<Book>() {

@Override

public int compare(Book o1, Book o2) {

return o1.id.compareTo(o2.id);

}

});

System.out.println(Arrays.asList(books));

}

输出量

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]

[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]

以上是 如何在Java中对对象数组进行排序? 的全部内容, 来源链接: utcz.com/qa/425954.html

回到顶部