码迷,mamicode.com
首页 > 其他好文 > 详细

集合的比较器

时间:2014-12-01 19:04:23      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:io   ar   sp   java   on   art   bs   cti   ad   

这个是现学现用的。


public class Student {
private String name;

private int age;

public Student(int age) {
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 boolean equals(Object obj) {
if(obj instanceof Student){
obj = (Student) obj;
return ((Student) obj).getName().equals(getName())? true:false;
}
return false;

}


}

 

//这个很重要  这个就是排序的比较器  在这里是根据学生的年龄来排序的

import java.util.Comparator;

/**
* 比较器
* @author DELL
*
*/
public class StudentCompartor implements Comparator<Student>{


@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
if(o1.getAge()>o2.getAge()){ //升序
return 1;
}
return -1;
}

}

 

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

public class CollectionCompareDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student(20));
list.add(new Student(30));
list.add(new Student(10));
list.add(new Student(40));

Collections.sort(list, new StudentCompartor());  //排序 传入要排序的集合和比较器
Iterator<Student> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next().getAge());
}
}
}

 

输出的结果是:

10
20
30
40

 

集合的比较器

标签:io   ar   sp   java   on   art   bs   cti   ad   

原文地址:http://www.cnblogs.com/hjy9420/p/4135609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!