您的位置:首页 > 编程语言 > Java开发

Java中的自定义排序

2010-10-17 20:17 211 查看
package com.yenange.t2;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class CompareTest {

// 2. 现有一个类person有三个属性,分别是name,age,sex。有一个List对象,

// 保存了很多person对象的实例,请编写一个函数,对List里的实例进行排序。

// 条件:18岁以上的人,排序顺序:性别,年龄,姓名全部降序。

public static void main(String[] args) {

List<Person> list=new ArrayList<Person>();

list.add(new Person("Tom",28,"男"));

list.add(new Person("Jack",18,"男"));

list.add(new Person("Rose",70,"女"));

list.add(new Person("Smith",19,"男"));

list.add(new Person("Sissi",38,"女"));

System.out.println("处理及排序前:");

printList(list);

int num=list.size();

for (int i=0;i<num;i++) {

if (list.get(i).getAge()<=18) {

list.remove(list.get(i));

--num;

}

}

System.out.println("按姓名排序:");

Person.setCompareType(Person.nameType);

Collections.sort(list);

printList(list);

System.out.println("按年龄排序:");

Person.setCompareType(Person.ageType);

Collections.sort(list);

printList(list);

System.out.println("按性别排序:");

Person.setCompareType(Person.sexType);

Collections.sort(list);

printList(list);

}

private static void printList(List<Person> list) {

for (Person person : list) {

System.out.println(person);

}

}

}

class Person implements Comparable<Person>{

private static int compareType=1;

public static final int nameType=1;

public static final int ageType=2;

public static final int sexType=3;

private String name;

private int age;

private String sex;

public Person() {

}

public Person(String name, int age, String sex) {

this.name = name;

this.age = age;

this.sex = sex;

}

public String toString() {

return "姓名: "+name+"/t年龄:"+age+"/t性别:"+sex;

}

public int compareTo(Person p) {

if (compareType==nameType) {

return this.name.compareTo(p.name);

}else if (compareType==ageType) {

return this.age-p.age;

}

return this.sex.compareTo(p.sex);

}

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 String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

public static int getCompareType() {

return compareType;

}

public static void setCompareType(int compareType) {

Person.compareType = compareType;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: