Comparable和Comparator的区别

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Comparable和Comparator的区别相关的知识,希望对你有一定的参考价值。

Comparable

Comparable是由需要比较的类自己实现(implements)此接口,并实现其中的compareTo方法,之后对象可直接使用Collection.sort方法进行排序等

public class OrgNode implements Comparable {
    private Logger log = LoggerFactory.getLogger(OrgNode.class);

    private long orgId;
    private String name;
    private long sortId;

    private List<OrgNode> children = new ArrayList<OrgNode>();

    public OrgNode(long orgId, String name) {
        this.orgId = orgId;
     this.name = name;
    }

    public List<OrgNode> getChildren() {
        if (children == null) {
            children = new ArrayList<OrgNode>();
        }

        Collections.sort(children);

        return Collections.unmodifiableList(children);
    }
  
    @Override
    public int compareTo(Object obj) {
        OrgNode orgNodeTmp = (OrgNode) obj;
        return new Long(this.sortId).compareTo(orgNodeTmp.sortId);
    }
  public long getOrgId() {
      return orgId;
  }

  public String getName() {
      return name;
  }

  public long getSortId() { return sortId; } 

  public void setSortId(long sortId) { this.sortId = sortId; }
}

 

Comparator

Comparator是在需要比较类的外面自定义的一个比较器,并实现compare方法。在使用Collection.sort时,把实现的比较器当作第二个参数传入:

public class OrgNodeComparator implements Comparator<OrgNode> {

    @Override
    public int compare(OrgNode o1, OrgNode o2) {
        return new Long(o1.getSortId()).compareTo(o2.getSortId());
    }
    
}
public class OrgNode {
    private Logger log = LoggerFactory.getLogger(OrgNode.class);

    private long orgId;
    private String name;
    private long sortId;

    private List<OrgNode> children = new ArrayList<OrgNode>();

    public OrgNode(long orgId, String name) {
        this.orgId = orgId;
     this.name = name;
    }

    public List<OrgNode> getChildren() {
        if (children == null) {
            children = new ArrayList<OrgNode>();
        }

        Collections.sort(children, new OrgNodeComparator());
      return Collections.unmodifiableList(children);
    } 

   public long getOrgId() {   return orgId;   }
   public String getName() {   return name;   }
   public long getSortId() { return sortId; }
   public void setSortId(long sortId) { this.sortId = sortId; }
 }

 

以上是关于Comparable和Comparator的区别的主要内容,如果未能解决你的问题,请参考以下文章

Java中Comparable与Comparator的区别

Java中Comparable与Comparator的区别

java中Comparable和Comparator区别和总结

Comparable和Comparator的区别

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

Java中Comparable和Comparator接口区别分析