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

Java基础知识强化之集合框架笔记69:Collections类之ArrayList存储自自定义对象并排序的案例

2015-10-10 14:11 846 查看
1. ArrayList存储自自定义对象并排序的案例:

ArrayList存储自自定义对象,并使用Collections对ArrayList存储基本包装类的元素排序。

2. 代码实现:

(1)Student.java:

 package cn.itcast_02;

/**
* @author Administrator
*
*/
public class Student implements Comparable<Student> {
private String name;
private int age;

public Student() {
super();
}

public Student(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
public int compareTo(Student s) {
int num = this.age - s.age;
int num2 = num == 0 ? this.name.compareTo(s.name) : num;
return num2;
}
}


(2)CollectionsDemo.java:

 package cn.itcast_02;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/*
* Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢?
*/
public class CollectionsDemo {
public static void main(String[] args) {
// 创建集合对象
List<Student> list = new ArrayList<Student>();

// 创建学生对象
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("风清扬", 30);
Student s3 = new Student("刘晓曲", 28);
Student s4 = new Student("武鑫", 29);
Student s5 = new Student("林青霞", 27);

// 添加元素对象
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);

// 排序
// 自然排序
// Collections.sort(list);
// 比较器排序
// 如果同时有自然排序和比较器排序,以比较器排序为主
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s2.getAge() - s1.getAge();
int num2 = num == 0 ? s1.getName().compareTo(s2.getName())
: num;
return num2;
}
});

// 遍历集合
for (Student s : list) {
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: