Sorting Lists1

package sortobjects;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
private String name;
private int id;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String toString() {
    return "Person [name=" + name + ", id=" + id + "]";
}

public Person(String name, int id) {

    this.name = name;
    this.id = id;
}

}

/ sort of objects with id
class Personsorting implements Comparator {

@Override
public int compare(Person p1, Person p2) {
    if (p1.getId() > p2.getId())
        return 1;
    else if (p1.getId() < p2.getId())
        return -1;
    return 0;
}

}

/// sort of String with length
class Lengthsorting implements Comparator {

@Override
public int compare(String s1, String s2) {
    if (s1.length() > s2.length())
        return 1;
    else if (s1.length() < s2.length())
        return -1;
    return 0;
}

}

public class ListSort {
public static void main(String[] args) {
// sort in objects
List people = new ArrayList<>();
people.add(new Person(“Bob”, 1));
people.add(new Person(“Sarah”, 7));
people.add(new Person(“Sue”, 4));

    Collections.sort(people, new Personsorting());
    for (Person person : people)
        System.out.println(person);

    // sort in String 1
    List<String> string = new ArrayList();
    string.add("one");
    string.add("two");
    string.add("three");
    Collections.sort(string, new Lengthsorting());
    System.out.println(string);
    // sort in String 2 with the
    // order in alphabet
    List<String> string2 = new ArrayList();
    string2.add("one");
    string2.add("two");
    string2.add("three");
    Collections.sort(string2);
    System.out.println(string2);

    / sort in Integer with the
    / natural order
    List<Integer> integer = new ArrayList();
    integer.add(5);
    integer.add(0);
    integer.add(2);
    Collections.sort(integer);
    System.out.println(integer);
}

}
String 和Integer 这两种封装类,都已经有确定的排序方式,利用Collections这个类调用sort的方法就可以进行排序,此时Collections只有一个参数
如果想改变这种排序方式,可以创建一个类,它的接口是Comparator,或者说是泛型Comparetor的方法只有一个(泛型就是一种接口,只不过可以通过改变<>中引用的类型来改变方法的参数),就是compare,compare的参数有两个,通过比较,可以返回0,1,-1,返回值不同,则Collections会根据第二个参数进行排序。
由此,可以知道,自定义的类没有自定的排序方式,因为field很多,不确定要用哪个排序,此时只能用String和Integer中的第二种方法来排序。

Supongo que te gusta

Origin blog.csdn.net/juttajry/article/details/48901859
Recomendado
Clasificación