JAVA排序
List<People> list = ...; //import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Person implements Comparable{
private int age;
private String name;
public Person() {
// TODO Auto-generated constructor stub
age=0;
name="";
}
Person(int age,String name){
this.age = age;
this.name =name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Person p = (Person)o;
if(this.name.compareTo(p.getName())>0){
return 1;
}
else if(this.name.compareTo(p.getName())<0){
return -1;
}
else{
if(this.age>p.getAge()){
return 1;
}
else if(this.age<p.getAge()){
return -1;
}
}
return 0;
}
}
public class TestSort {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>() ;
list.add(new Person(31,"zhangsan"));
list.add(new Person(13,"lisi"));
list.add(new Person(24,"wangwu"));
list.add(new Person(24,"lisi"));
Collections.sort(list);
for (Object o : list) {
Person p = (Person)o;
System.out.println(p.getName()+" "+p.getAge());
}
}
}有个保存了People类的Listimport java.util.List;
class Person implements Comparable{
private int age;
private String name;
public Person() {
// TODO Auto-generated constructor stub
age=0;
name="";
}
Person(int age,String name){
this.age = age;
this.name =name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Person p = (Person)o;
if(this.name.compareTo(p.getName())>0){
return 1;
}
else if(this.name.compareTo(p.getName())<0){
return -1;
}
else{
if(this.age>p.getAge()){
return 1;
}
else if(this.age<p.getAge()){
return -1;
}
}
return 0;
}
}
public class TestSort {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>() ;
list.add(new Person(31,"zhangsan"));
list.add(new Person(13,"lisi"));
list.add(new Person(24,"wangwu"));
list.add(new Person(24,"lisi"));
Collections.sort(list);
for (Object o : list) {
Person p = (Person)o;
System.out.println(p.getName()+" "+p.getAge());
}
}
Collections.sort(list, new Comparator<People>() { //排序
public int compare(People p1, People p2) {
if (p1.getName().compareTo(p2.getName()) == 0) { //如果名字相同
return p2.getAge() - p1.getAge(); //年龄降序
}
return p1.getName().compareTo(p2.getName()); //姓名升序
}
});
//这样list就排序好了,上述假设People类有getName方法获取姓名,getAge方法获取年龄
public int compare(People p1, People p2) {
if (p1.getName().compareTo(p2.getName()) == 0) { //如果名字相同
return p2.getAge() - p1.getAge(); //年龄降序
}
return p1.getName().compareTo(p2.getName()); //姓名升序
}
});
//这样list就排序好了,上述假设People类有getName方法获取姓名,getAge方法获取年龄