Java的排序:排序属性对象的数组,对象不准用可比 [英] Java Sorting: sort an array of objects by property, object not allowed to use Comparable

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

问题描述

我有一个类,图书馆,包含图书对象的数组,我需要根据关书的属性对数组进行排序,无论是标题还是的PageNumber。问题是我不是允许使用可比类图书。你会如何​​建议我的书籍在图书馆数组排序?写我自己的排序?还是有更简单的方法?如果您需要code的片段,只问!

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!

推荐答案

您可以提供一个比较比较任何你想要的类型,可比

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

有关数组和集合使用

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的排序:排序属性对象的数组,对象不准用可比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆