浅述数组排序
javascript
数组自带的函数sort可以根据自定义的排序器排序
function compare(v1, v2) {
return v1-v2;
}
var values = [4,1,2,5,3];
var vv = values.sort(compare);
console.info(vv);
java
如果有一个复杂数据类型的集合需要排序时,处理方式有两种
用Comparator定义一个比较器
- 定义一个Person类
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
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 class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
}
- 排序
List<Person> list = new ArrayList<Person>();
Collections.sort(list, new PersonComparator());
复杂数据类继承Comprable
- 复杂数据类重写compareTo(O)
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
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;
}
@Override
public int compareTo(Person o) {
return o.getAge()-this.getAge();
}
}
- 排序
List<Person> list = new ArrayList<Person>();
Collections.sort(list);
如果觉得文章对您有用,请点下推荐。您的支持将鼓励我继续创作!