java集合List集合使用Collections排序
硅谷探秘者
2019-08-12发表
0
0
3827
有Student类,一个List集合中有若干Student对象,对此集合按分数排序
Student
package com.example.demo.entity;
@SuppressWarnings("rawtypes")
public class Student implements Comparable{
private int id;
private String name;
private float score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public Student(int id, String name, float score) {
super();
this.id = id;
this.name = name;
this.score = score;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
@Override
public int compareTo(Object o){
// TODO Auto-generated method stub
if(o instanceof Student) {
Student s=(Student)o;
if(s.getScore()>this.getScore()) {
return 1;
}else if(s.getScore()<this.getScore()){
return -1;
}else {
return 0;
}
}else {
try {
throw new Exception("比较异常");
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
}
要想使用Collections.sort(l); 排序 Student类必须实现Comparable接口,如上,返回1本对象大于比较对象,-1代表小于比较对象。
@Override
public int compareTo(Object o){
// TODO Auto-generated method stub
if(o instanceof Student) {
Student s=(Student)o;
if(s.getScore()>this.getScore()) {
return 1;
}else if(s.getScore()<this.getScore()){
return -1;
}else {
return 0;
}
}else {
try {
throw new Exception("比较异常");
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
测试
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.example.demo.entity.Student;
public class Test2Controller {
@SuppressWarnings("unchecked")
@Test
public void test() {
List<Student> l=new ArrayList<Student>();
for(int i=0;i<1000;i++){
l.add(new Student(i,"test"+i,(float)Math.round((Math.random()*10000))/100));
}
long t=0;
t-=System.currentTimeMillis();
Collections.sort(l);
t+=System.currentTimeMillis();
System.out.println("time:"+t);
for(Student s:l) {
System.out.print(s.getScore()+" ");
}
}
}