//对整数集合进行排序
public void sortIntArray() {
int[] array = new int[] { 8, 5, 9, 0, 6, 3, 4, 7, 2, 1 };
System.out.println("整数排序前");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
Arrays.sort(array);
//对字符串集合进行排序
String[] array = new String[] { "a", "c", "e", "d", "b" };
System.out.println("字符串排序后");
Arrays.sort(array);
//对集合进行排序
java对集合排序的方法主要有两种,分别为实现Comparator接口和实现Comparable接口。其中,实现Comparable接口比较简单,用于单一标准的排序。如:
public class Animals implements Comparable
private String name;
public int age;
public Animals(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
LinkedList
list.add(new Animals("a", 2));
list.add(new Animals("b", 4));
list.add(new Animals("c", 6));
Collections.sort(list);//需重写compareTo()方法
for (Animals animals : list) {
System.out.println("Animals name=" + animals.name + "age="
+ animals.age);
}
}
@Override
public int compareTo(Animals o) {
if (this.age > o.age)
return 1;
if (this.age < o.age)
return -1;
else
return 0;
}
}
但如果要实现多种要求的排序,就要实现Comparator接口了。因为Comparable接口只能用一种方式比较。实现Comparator接口,如:
Collections.sort(list, new AnimalsComparator());//sort方法的两个参数:比较的集合,比较器类的对象。
//比较器类,实现compare()方法
class AnimalsComparator implements Comparator
@Override
public int compare(Animals o1, Animals o2) {
if (o1.age > o2.age)
return 1;
if (o1.age < o2.age)
return -1;
else
return 0;
}
}
这样,通过构建不同的比较器类,并在sort()方法里面传入不同的比较器类对象,就能实现对象的不同属性比较。上面是按年龄,如果按体重也可以,如:
Collections.sort(list, new AnimalsWeightComparator());
class AnimalsWeightComparator implements Comparator
@Override
public int compare(Animals o1, Animals o2) {
if (o1.weight> o2.weight)
return 1;
if (o1.weight< o2.weight)
return -1;
else
return 0;
}
}
当然PO类要有对应的属性,并为属性传入参数。
用Collections.sort方法对list排序有两种方法
第一种是list中的对象实现Comparable接口,如下:
public
class
User
implements
Comparable
{
private
String name;
private
Integer order;
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
public
Integer getOrder() {
return
order;
}
public
void
setOrder(Integer order) {
this
.order = order;
}
public
int
compareTo(User arg0) {
return
this
.getOrder().compareTo(arg0.getOrder());
}
}
|
Collections.sort(list);