java中使用sort()对ArrayList进行排序
来源:互联网 发布:高中网络课程 编辑:程序博客网 时间:2024/05/19 01:09
java中的ArrayList需要通过collections类的sort方法来进行排序
如果想自定义排序方式则需要有类来实现Comparator接口并重写compare方法
调用sort方法时将ArrayList对象与实现Commparator接口的类的对象作为参数
举个例子:
package book.arrayset;import java.util.Comparator;/*** 整数比较器,将整数按降序排列*/class MyIntComparator implements Comparator{/*** o1比o2大,返回-1;o1比o2小,返回1。*/public int compare(Object o1, Object o2) {int i1 = ((Integer)o1).intValue();int i2 = ((Integer)o2).intValue();if (i1 < i2){return 1;}if (i1 > i2){return -1;}return 0;}}//上面的为比较的函数实现,下面真正的添加数据,//通过调用上面的比较函数实现自定义排序的功能package book.arrayset;import java.util.ArrayList;import java.util.Collections;import java.util.List;/*** 对List中的元素排序*/public class SortList {public static void output(List list){if (list == null){return;}for (int i=0; i<list.size(); i++){System.out.print(list.get(i).toString() + " ");}System.out.println();}public static void main(String[] args) {List list = new ArrayList();list.add(new Integer(5));list.add(new Integer(8));list.add(new Integer(1));list.add(new Integer(3));list.add(new Integer(2));list.add(new Double(3.1));
<span style="font-family: Arial, Helvetica, sans-serif;">System.out.println("list开始状态");</span>
SortList.output(list);
//Collections.sort <span style="color:#ff0000;">用默认比较器排列list的元素</span>Collections.sort(list);System.out.println("list被默认比较器排序后的状态");SortList.output(list);
//用自定义方法按降序排列</span>Collections.sort(list, new MyIntComparator());System.out.println("list被自定义比较器排序后的状态");SortList.output(list);}}
因此,对于任意自定义类的对象,当保存在集合类容器中后,如果需要对它们进行排序,需要自己提供适应于自定义类的比较器,自定义比较器必须实现Comparator接口。然后采用Collections.sort(list, comparator);方法对容器进行排序。</span>
0 0
- java中使用sort()对ArrayList进行排序
- 使用Collections.sort()对List/ArrayList进行排序
- java中对ArrayList进行排序
- Java中对ArrayList进行排序
- java中对ArrayList进行排序
- *使用Java语言实现对ArrayList进行排序
- Java使用Collections.sort对一个列表进行自定义排序
- 对ArrayList中某一元素进行排序
- 使用Comparator对ArrayList进行排序
- java对arrayList中的元素进行排序
- 使用sort方法对数组进行排序
- 使用Collections.sort对集合进行排序。
- 使用Collections.sort对List进行排序
- java 排序 ArrayList sort方法
- JAVA中对ArrayList的排序
- 如何使用arraylist对存放class中某个元素进行排序
- Java 基础小知识二:使用Comparator 对ArrayList 进行排序
- Java中应用Collections工具类的Sort()方法对List进行排序
- c++学习笔记 第二天
- Adobe flash player 因过期而遭到阻止 解决办法
- 二叉树相关算法
- 经典算法之-----贪心算法
- UI优化技巧:使用layoutopt进行布局优化
- java中使用sort()对ArrayList进行排序
- eclipse配置maven
- switch用法(这个感觉很容易理解)
- 【leetcode】subsets
- 第2周项目3(1)——两种排序算法的运行时间
- C++中的 cout 和cin
- 数据结构—Java版链表相交问题的终极解决方案
- 黑马程序员--------Java基础-----数组和类
- hdu Travel