首页 > 代码库 > Comparable和Comparator的区别

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的区别