【发布时间】:2015-12-20 09:07:53
【问题描述】:
我想使用我创建的排序函数按年龄对学生进行排序,但我不确定是否需要在这部分实现比较器/可比较。
我有以下 POJO:
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
创建了一个界面:
public interface CollectionsProblem {
public void sort(Collection<Student> memes, boolean ascending);
}
这是接口的实现:
public class CollectionsProblemImpl implements CollectionsProblem {
public void sort(Collection<Student> students, boolean ascending) {
/****Need to add some sorting here in order to sort students by age
param0 - students: the collection to sort
param1 - ascending: true if the collection should be sorting in ascending order, otherwise false***
*/
}
}
【问题讨论】:
-
如果是你自己的排序算法,你可以随心所欲。但是,就地对集合进行排序没有意义:例如,您将永远无法对 HashSet 进行排序,因为 HashSet 元素在集合中没有任何索引。该方法应该将 List 作为参数。或者它应该采用一个集合,但创建一个排序的副本并因此返回一个列表。
标签: java sorting collections