甲乙小朋友的房子

甲乙小朋友很笨,但甲乙小朋友不会放弃

0%

Java-Comparable接口

Arrays类中的sort方法可以对对象数组进行排序。但前提是对象所属的类必须实现了Comparable接口。

接口代码

1
2
3
public interface Comparable{
int compareTo(Object other);
}

为了让某个类实现以上Comparable接口,通常需要以下两个步骤:

  1. 将类声明为实现给定的接口;
  2. 对接口中的所有方法进行定义。

例子

这个Node内有两个变量:key和count。如果我们想通过count来定义大小的话,我们这么写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Node implements Comparable<Node>{
int key;
int count;
@Override
public int compareTo(Node o){
if(this.count > o.count){
return 1;
}else if(this.count == o.count){
return 0;
}else{
return -1;
}
}
}

String 的compareTo

如果要比较字符串的字典顺序,那就使用:

1
2
3
s1 = "ab";
s2 = "ac";
s1.compareTo(s2); //return -1,s1在s2前