Arraylist如何实现排序

2025-07-12 01:44:31

1、总结:使用Collections.sort()传入ArrayList,会采用默认的方式进行排序(字典序)使用Collections.sort()传入ArrayList和自己实现Commparator接口的类的对象,实现自定义排序

Arraylist如何实现排序

2、使用List.sort()传入自己实现Commparator接口的类的对象,实现自定义排序Comparator返回值在jdk1.7、jdk1.8里必须是一对相反数,如1和-1,不能是1和0.因为1.7的排序算法采用timsort,对返回值有严格要求http://baike.baidu.com/link?url=UCowuf65GHz3cWVf_d7t0QzYUCcwU0QUwserNTIrImlaTBvBAaVfywzppQ70DqWKzUu3dPqsF21k9IDpT8QPE_

Arraylist如何实现排序

3、importjava.util.*;publicclassTestArrayListSort{@SuppressWarnings("unchecked")publicst锾攒揉敫aticvoidmain(String[]args){//TODOAuto-generatedmethodstubListlistInt=newArrayList(),listStr=newArrayList();//自定义Comparator对象,自定义排序Comparatorc=newComparator<Integer>(){@Overridepublicintcompare(Integero1,Integero2){//TODOAuto-generatedmethodstubif((int)o1<(int)o2)return1;//注意!!返回值必须是一对相反数,否则无效。jdk1.7以后就是这样。//elsereturn0;//无效elsereturn-1;}

Arraylist如何实现排序

4、 };listInt.add(2);listInt.add(4);listInt.add(9);listInt.add(5);listStr.add("haha");listStr.add("hehe");listStr.add("ao");listStr.add("Ti");@SuppressWarnings("rawtypes")Listlist01=newArrayList(listInt);Listlist02=newArrayList(listInt);Collections.sort(listInt);Collections.sort(listStr);list01.sort(c);Collections.sort(list02,c);System.out.println(listInt);System.out.println(listStr);System.out.println(list01);System.out.println(list02);}}

Arraylist如何实现排序

5、输出:[2, 4, 5, 9][Ti, ao, haha, hehe][9, 5, 4, 2][9, 5, 4, 2]

Arraylist如何实现排序
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢