番石榴比较链与列表?

时间:2012-08-13 20:07:58

标签: java guava

我正在尝试使用ComparisonChain在类中实现compareTo(),但是该类包含List,而compare()不接受它们,因为List没有实现Comparable。关于如何使这项工作的任何想法?

代码子集看起来像这样:

public class User() {
  String name;
  List<String> emails;

  ...

  public int compareTo(User that) {
    return ComparisonChain().start()
                            .compare(this.name, that.name)
                            .compare(this.emails, that.emails)  // Fails on this line
                            .result();
  }
}

1 个答案:

答案 0 :(得分:13)

ComparisonChain.start()
    .compare(this.name, that.name)
    .compare(this.emails, that.emails,
       Ordering.<String>natural().lexicographical())
    .result();