关闭

Java-Collections的sort方法对 list 进行排序

168人阅读 评论(0) 收藏 举报
分类:


    1.List中的对象实现Comparable接口:

public class User implements Comparable<User>
{
	    private String name;
	    private Integer order;
	    public String getName() {
	        return name;
	    }
	    public void setName(String name) {
	        this.name = name;
	    }
	    public Integer getOrder() {
	        return order;
	    }
	    public void setOrder(Integer order) {
	        this.order = order;
	    }
	    public int compareTo(User arg0) {
	        return this.getOrder().compareTo(arg0.getOrder());
	    }

}
下面是测试类Test:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class Test{
	 
	    public static void main(String[] args) {
	        User user1 = new User();
	        user1.setName("a");
	        user1.setOrder(1);
	        User user2 = new User();
	        user2.setName("b");
	        user2.setOrder(2);
	       
	       List<User> list = new ArrayList<User>();
	        //此处add user2再add user1
	        list.add(user2);
	        list.add(user1);
	        Collections.sort(list);
	        for(User u:list){
	            System.out.println(u.getName());
	        }
	    }
	}
输出为:

a

b

2.使用静态内部类实现Comparator接口,Comparator接口位于java.util包下

import java.util.*;
public class Main{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(2,"aa"));
al.add(new Student(1,"bb"));
al.add(new Student(3,"dd"));
al.add(new Student(3,"cc"));
Collections.sort(al,new StudentComparator());
Iterator it=al.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class Student {
int id;
String name;
Student(int id,String name){
this.id=id;
this.name=name;
}
public String toString(){
return "id="+this.id+",name="+this.name;
}
}
class StudentComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
int result=(s1.id>s2.id)?1:((s1.id==s2.id)?0:-1);
if(0==result){
result=s1.name.compareTo(s2.name);
}
return result;
}
}

3.补充:我遇到的情况是直接List<String> list=new ArrayList();

在这种情况下,我们如果调用Collections.sort(list);方法,它会对list里字符串从左往右的字母的ascii值进行排序,不用实现 Comparator 接口。

public class Connectionssort {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<String> list = new ArrayList();
		int j=0;
		JDBManager db=new JDBManager();	
		ResultSet rs;
		String q = "select * from securityEvent";
		try {
			rs = db.executeQuery(q);
			while (rs.next()) {
				list.add(rs.getString("grade"));
			}
			Collections.sort(list);
			while (j < list.size()) {
					System.out.println(list.get(j).toString());
					j++;
				}
	}catch (Exception e) {
		// TODO: handle exception
	}
}
}
实验结果如下:

A

A

B

B

B

C

C

C

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:218414次
    • 积分:4022
    • 等级:
    • 排名:第7748名
    • 原创:89篇
    • 转载:548篇
    • 译文:13篇
    • 评论:7条
    最新评论