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

Java中的comparable接口和Comparator接口的区别

2018-08-01 11:30 441 查看

一.comparable和Comparator的区别

  1、Comparable和Comparator都是用来实现集合中元素的比较、排序的。

  2、Comparable是在类内部定义的方法实现的排序,位于java.lang下。

  3、Comparator是在类外部实现的排序,位于java.util下。

  4、实现Comparable接口需要覆盖compareTo方法,实现Comparator接口需要覆盖compare方法。

  5、Comparable接口将比较代码嵌入需要进行比较的类的自身代码中,而Comparator接口在一个独立的类中实现比较。

二.深度认识

 首先Comparable这个接口是使用在你需要排序的元素类上的。

 而Comparator不是使用在你需要排序的元素类上的,它需要实现一个子类对象,将子类对象传入可以排序的集合中(TreeSet)。

 当你想去使用comparable接口时必须去修改源代码,因为他是建立在需要被排序的元素类上的。

那你要是想对String类进行你自己想要的排序怎么办呢?(举例子,不要抬杠)

首先你不能去修改源代码,第二String类是final类不能继承。

那么此时你就可以使用Comparator接口实现在类外的排序

三.实例

1.对元素类Node实现comparable接口

package com.cjm.lambda;

import java.util.Set;
import java.util.TreeSet;
/**
*
* @author 小明
*
*/
public class SetSortlambda {
public static void main(String[] args) {
Set<Node> set = new TreeSet<>();
set.add(new Node("zs",10));
set.add(new Node("zs1",110));
set.add(new Node("zs1",10));
set.add(new Node("zszx",100));
set.add(new Node("zzxs",10));
System.out.println(set);
}
}
/*
* 元素本生实现comparator接口
*/
class Node implements Comparable<Node> {
int num;
String str;

public Node(String str,int num) {
this.str=str;
this.num = num;
}

@Override
public int compareTo(Node o) {
if (this.str == null) {
return -1;
} else {
if (o.str == null) {
return 1;
} else {
if (this.str.length() < o.str.length()) {
return -1;
} else {
if (this.str.length() > o.str.length()) {
return 1;
} else {
if (this.num < o.num) {
return -1;
} else {
if (this.num > o.num) {
return 1;
} else {
return 0;
}
}
}
}
}
}

}

/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return  str+num;
}

}

 

2.使用Comparator接口,实现一个Comparator接口的对象(采用内部类的方式)

package com.cjm.lambda;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
* Compararator接口实现排序
*
* @author 小明
*
*/

public class Text {
public static void main(String[] args) {
Set<Node> set = new TreeSet<>(new Comparator<Node>() {

@Override
public int compare(Node node1, Node node2) {
if (node1.str.length() < node2.str.length()) {
return 1;
} else {
if (node1.str.length() > node2.str.length()) {
return -1;
} else {
if (node1.num < node2.num) {
return 1;
} else {
if (node1.num > node2.num) {
return -1;
} else {
return 0;
}
}
}
}
}
});
set.add(new Node("zs", 10));
set.add(new Node("zs1", 110));
set.add(new Node("zs1", 10));
set.add(new Node("zszx", 100));
set.add(new Node("zzxs", 10));
System.out.println(set);
}
}

 

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