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中的第二种方法来排序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值