关于java的Comparable和Comparator的使用
Comparable的使用:需要进行排序的类使用Comparable接口,重写compareTo方法
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparable;
public class TestComparable {
public static void main(String[] args){
List<Desk> list=new ArrayList<Desk>();
list.add(new Desk("hello"));
list.add(new Desk("hi"));
list.add(new Desk("hao"));
Collections.sort(list);
for(Desk temp:list){
System.out.println(temp.getName());
}
}
}
class Desk implements Comparable<Desk>{
private String name;
public Desk(String name){
this.name=name;
}
public String getName(){
return this.name;
}
@Override
public int compareTo(Desk o) {
return this.getName().compareTo(o.getName());
}
}
Comparator的使用:需要单独定义一个比较的类,该类实现Comparator接口,重写compare方法,用该新定义的类作为比较器
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestComparator {
public static void main(String[] args){
List<Desk> list=new ArrayList<Desk>();
list.add(new Desk("hi"));
list.add(new Desk("hao"));
list.add(new Desk("hello"));
Collections.sort(list,new CompDesk());
for(Desk temp:list){
System.out.println(temp.getName());
}
}
}
class Desk{
String name;
public Desk(String name){
this.name=name;
}
public String getName(){
return this.name;
}
}
class CompDesk implements Comparator<Desk>{
@Override
public int compare(Desk o1, Desk o2) {
return o1.getName().compareTo(o2.getName());
}
}
在其他需要比较的容器中也可以使用上述两种方法实现比较,如TreeSet和TreeMap
Comparable的使用:需要进行排序的类使用Comparable接口,重写compareTo方法
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparable;
public class TestComparable {
public static void main(String[] args){
List<Desk> list=new ArrayList<Desk>();
list.add(new Desk("hello"));
list.add(new Desk("hi"));
list.add(new Desk("hao"));
Collections.sort(list);
for(Desk temp:list){
System.out.println(temp.getName());
}
}
}
class Desk implements Comparable<Desk>{
private String name;
public Desk(String name){
this.name=name;
}
public String getName(){
return this.name;
}
@Override
public int compareTo(Desk o) {
return this.getName().compareTo(o.getName());
}
}
Comparator的使用:需要单独定义一个比较的类,该类实现Comparator接口,重写compare方法,用该新定义的类作为比较器
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestComparator {
public static void main(String[] args){
List<Desk> list=new ArrayList<Desk>();
list.add(new Desk("hi"));
list.add(new Desk("hao"));
list.add(new Desk("hello"));
Collections.sort(list,new CompDesk());
for(Desk temp:list){
System.out.println(temp.getName());
}
}
}
class Desk{
String name;
public Desk(String name){
this.name=name;
}
public String getName(){
return this.name;
}
}
class CompDesk implements Comparator<Desk>{
@Override
public int compare(Desk o1, Desk o2) {
return o1.getName().compareTo(o2.getName());
}
}
在其他需要比较的容器中也可以使用上述两种方法实现比较,如TreeSet和TreeMap