java集合排序

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

/*
 * Arrays.sort()
 * Connections.sort()
* 这里 一个 .java 文件里面有两个 public 其中一个是 内部类
*/ public class Test2 { static int[] n = {6,5,8,9,4,2,3,7,0}; static List<String> list = new ArrayList<String>(); static List<A> list2 = new ArrayList<A>(); public Test2(){ } public static void main(String args[]){ for(int i : n){ list.add(i+""); } list2.add(new A(1,"a")); list2.add(new A(5,"f")); list2.add(new A(4,"e")); list2.add(new A(2,"b")); list2.add(new A(3,"d")); Arrays.sort(n); System.out.println(Arrays.toString(n)); Collections.sort(list); System.out.println(list); Collections.sort(list2, new Comparator<A>() { @Override public int compare(A o1, A o2) { // TODO Auto-generated method stub // return o1.getName().compareTo(o2.getName()); return o1.getId().compareTo(o2.getId()); } }); System.out.println(list2); } public static class A{ private Integer id; private String name; public A(){} public A(int id, String name){ this.id = id; this.name = name; } public Integer getId(){ return this.id; } public void setId(Integer id){ this.id = id; } public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public String toString(){ return "id : "+id+" name : "+name; } } }
 控制台
[0, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 3, 4, 5, 6, 7, 8, 9]
[id : 1 name : a, id : 2 name : b, id : 3 name : d, id : 4 name : e, id : 5 name : f]

 

posted on 2014-08-25 16:29  Love I Smile  阅读(177)  评论(0编辑  收藏  举报