实体类:
package com.lzu.lession;
/**
* student 实体类
*
* @author xizepeng
* @date 2018年7月14日
*/
public class Student implements Comparable
private int stdId;
private String stdName;
private char stdSex;
private int stdAge;
public Student(int stdId, String stdName, char stdSex, int stdAge) {
super();
this.stdId = stdId;
this.stdName = stdName;
this.stdSex = stdSex;
this.stdAge = stdAge;
}
public int getStdId() {
return stdId;
}
public void setStdId(int stdId) {
this.stdId = stdId;
}
public String getStdName() {
return stdName;
}
public void setStdName(String stdName) {
this.stdName = stdName;
}
public char getStdSex() {
return stdSex;
}
public void setStdSex(char stdSex) {
this.stdSex = stdSex;
}
public int getStdAge() {
return stdAge;
}
public void setStdAge(int stdAge) {
this.stdAge = stdAge;
}
@Override
public int compareTo(Student o) {
// 先按照年龄排序
int i = this.getStdAge() - o.getStdAge();
if (i == 0) {
// 如果年龄相等了再用学号进行排序
return this.stdId - o.getStdId();
}
return i;
}
}
二、创建对象并输出
package com.lzu.lession;
/**
* 为实体类创建对象并用三种方法排序输出
*
* @author xizepeng
* @date 2018年7月15日
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestStudent {
public static void main(String[] args) {
List
list.add(new Student(001, "李紅", '男', 18));
list.add(new Student(024, "洋洋", '女', 17));
list.add(new Student(002, "李松", '男', 20));
list.add(new Student(012, "王燕", '男', 24));
list.add(new Student(015, "欣雨", '女', 22));
System.out.println("第一种排序:");
Collections.sort(list);
for (Student std : list) {
System.out.println(std.getStdId() + "," + std.getStdName() + "," + std.getStdSex() + ","
+ std.getStdAge());
}
System.out.println();
System.out.println("第二种排序:");
Collections.sort(list, new Comparator
@Override
public int compare(Student o1, Student o2) {
int i = o1.getStdId() - o2.getStdId();
if (i == 0) {
return o1.getStdAge() - o2.getStdAge();
}
return i;
}
});
for (Student stu : list) {
System.out.println("学号:" + stu.getStdId() + " " + "姓名:" + stu.getStdName() + " " + "性别:" + stu.getStdSex()
+ " " + "年龄:" + stu.getStdAge());
}
System.out.println();
// 冒泡排序
for (int i = 0; i < list.size(); i++) {
for (int j = i; j < list.size(); j++) {
if (list.get(i).getStdAge() < list.get(j).getStdAge()) {
Student container = list.get(i);
list.set(i, list.get(j));
list.set(j, container);
}
}
}
System.out.println("第三种排序:(年龄)");
for (Student stu : list) {
System.out.println("学号:" + stu.getStdId() + " " + "姓名:" + stu.getStdName() + " " + "性别:" + stu.getStdSex()
+ " " + "年龄:" + stu.getStdAge());
}
}
}