本文介绍了Java排序:按属性对对象数组进行排序,对象不允许使用Comparable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class, Library, that contains an array of Book objects, and I need to sort the array based off the properties of Book, either Title or PageNumber. The problem is im not allowed to use the Comparable class with Book. How would you recommend I sort the array of Books in library? Write my own sort? Or is there an easier way? If you need snippets of code, just ask!

推荐答案

您可以提供一个 Comparator 来比较您希望的任何类型,Comparable 或其他.

You can provide a Comparator for comparing any type you wish, Comparable or otherwise.

对于你使用的数组和集合

For Arrays and Collections you use

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

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

Even sorted collections like TreeSet can take a custom Comparator

例如

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
   }
});

这篇关于Java排序:按属性对对象数组进行排序,对象不允许使用Comparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:35