首页 > 代码库 > 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的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。