您的位置:首页 > 编程语言 > Java开发

Java集合中Comparable与Comparator

2016-03-25 16:45 393 查看
简单说,Comparable是默认比较规则的接口。

实现了这个接口可以比较大小,可以自然排序

实现需要重写方法:CompareTo()。

返回值为正数(大于),0(相等),负数(小于)。

看下面代码:

import java.util.*;

public class Student implements Comparable<Student> {

private String name;

private int age;

public Student() {
}

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public int compareTo(Student o) {
if ( getAge() > o.getAge()) {
return 1;
} else if ( getAge() < o.getAge()) {
return -1;
} else {
return 0;
}
}

//重写toString() 用于输出
public String toString() {
return  name +":"+age ;
}


在main方法中

Student s1 = new Student("Tom", 25);
Student s2 = new Student("Jim", 18);

List<Student> studentList = new ArrayList<Student>();
studentList.add(s1);
studentList.add(s2);

Collections.sort(studentList);
System.out.printf(studentList);


关于Comparator

用于临时的一些比较规则,需要自定义。

实现该接口需要实现Compare()方法

3.看代码

public class StudentComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
if (o1.getAge() > o2.getAge()) {
return 1;
}else if (o1.getAge() == o2.getAge()) {
return 0;
}else{
return -1;
}
}

在main方法中


Student s1 = new Student(“Tom”, 25);

Student s2 = new Student(“Jim”, 18);

StudentComparator comparator = new StudentComparator();

System.out.println(comparator.compare(s1 , s2));

“`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: