当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

字符串、list 排序 comparable

发表于: 2012-10-14   作者:cuityang   来源:转载   浏览:
摘要: package test; import java.util.*; public class SortTest { private List<Student> lista = new ArrayList<Student>(); /** * @param args * @CreateDate:2012-10-14 * @author *
package test;
import java.util.*;

public class SortTest {

private List<Student> lista = new ArrayList<Student>();

/**
* @param args
* @CreateDate:2012-10-14
* @author
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
simpleSort();

SortTest s = new SortTest();
s.listSort();
}

/**
* 字符串排序,基本用不上
* @CreateDate:2012-10-14
* @author
*/
public static void simpleSort(){
String[] strs = {"abb","dfs","adc"};

Arrays.sort(strs);
System.out.println(strs[0]+","+strs[1]+","+strs[2]);
}

/**
* list排序
* @CreateDate:2012-10-14
* @author
*/
public void listSort(){
this.lista.add(new Student("abb"));
this.lista.add(new Student("dfs"));
this.lista.add(new Student("adc"));

Collections.sort(this.lista);
for(Student s:lista){
System.out.println(s.name);
}

//降序
Comparator comp = Collections.reverseOrder();
Collections.sort(this.lista,comp);
for(Student s:lista){
System.out.println("降序:"+s.name);
}
}

}

class Student implements Comparable<Student>{

public String name;

public Student(String name){
this.name = name;
}

@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub

return this.name.compareTo(((Student)o).name);
}


}

结果:
abb,adc,dfs
abb
adc
dfs
降序:dfs
降序:adc
降序:abb

字符串、list 排序 comparable

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号