有关在Java中对自定义对象进行排序的完整指南。 Collections.sort()方法基于Comparable或Comparator实现进行排序。 用于对Employee对象进行排序的示例自定义排序
1.简介
在本教程中,您将学习如何在java中对Custom对象进行排序 。 首先,我们将显示示例程序以对字符串列表进行排序,然后移至
自定义Employee的Arraylist的排序 。 排序由Empoyee完成
ID,姓名和年龄 。 本文末尾显示的所有示例均在GitHub上。
2. Collections.sort()示例
Collections类具有一个sort()方法,该方法采用List实现,例如ArrayList , LinkedList等。
现在,创建一个带有字符串值的列表,并使用Collections.sort()方法对这些值进行排序。
默认情况下,Collections.sort()方法以升序进行排序。 所有添加到列表中的值必须实现Comparable接口。
如果将null传递给sort()方法,它将抛出java.lang.NullPointerException 。
2.1字符串排序表
package com.java.w3schools.blog.collections; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /**
*
* Collections.sort() example to sort List of Strngs.
*
* @author JavaProgramTo.com
*
*/ public class CollectionSortExample {
public static void main(String[] args) {
List<String> countries = new ArrayList<>();
countries.add( "Singapore" );
countries.add( "India" );
countries.add( "USA" );
countries.add( "UK" );
countries.add( "Australia" );
System.out.println( "List of countires before sorting : " );
Iterator<String> it = countries.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Collections.sort(countries);
System.out.println( "List of countries after sorting :" );
it = countries.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
} }
输出:
List of countires before sorting : Singapore India USA UK Australia List of countries aft