字符串、list 排序 comparable

本文通过具体示例介绍了如何在Java中实现字符串数组及自定义对象列表的排序操作,包括使用Arrays.sort()进行简单排序和利用Collections.sort()配合自定义比较器实现更复杂的排序逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值