[Java] 纯文本查看 复制代码
package com.heima.dianzhao;
import java.util.ArrayList;
import java.util.Collections;
import java.util.TreeSet;
import javax.swing.plaf.metal.MetalIconFactory.TreeLeafIcon;
public class Test4 {
public static void main(String[] args) {
ArrayList<User> list = new ArrayList<User>();//当然也可以用匿名内部类来重写compareTo方法
list.add(new User("赵六",26));
list.add(new User("张三",23));
list.add(new User("王五",25));
list.add(new User("李四",24));
// demo1(list); //方法一:使用TreeSet集合进行排序
/* Collections.sort(list); //方法二:使用Collections集合工具类对ArrayList集合进行排序
System.out.println(list);*/
// demo2(list); //方法三:使用选择或者冒泡排序对ArrayList集合中的元素进行排序
demo3(list);
}
private static void demo3(ArrayList<User> list) { //冒泡排序法
for (int i = 0; i < list.size()-1; i++) {
for (int j = 0; j < list.size()-1-i; j++) {
if (list.get(j).getAge() < list.get(j+1).getAge()) {
User temp = list.get(j);
User temp2 = list.get(j+1);
list.set(j, temp2);
list.set(j+1,temp);
}
}
}
System.out.println(list);
}
private static void demo2(ArrayList<User> list) { //选择排序法
for (int i = 0; i < list.size()-1; i++) {
for (int j = i+1 ; j < list.size(); j++) {
if (list.get(i).getAge() < list.get(j).getAge()) {
User temp = list.get(i);
User temp2 = list.get(j);
list.set(i, temp2);
list.set(j, temp);
};
}
}
System.out.println(list);
}
private static void demo1(ArrayList<User> list) { //用TreeSet集合排序
TreeSet<User> set = new TreeSet<User>();
set.addAll(list);
list.clear();
list.addAll(set);
System.out.println(list);
}
}
class User implements Comparable<User> { //定义一个User类
private String name;
private int age;
public User() { //空参构造
super();
}
public User(String name, int age) { //有参构造
super();
this.name = name;
this.age = 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;
}
@Override //重写toString()
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
@Override //重写compareTo()方法
public int compareTo(User o) {
int num = o.age - this.age;
return num == 0 ? o.name.compareTo(this.name):num;
}
}