使用自定义比较器,每次实例化它是否有任何优势,而不是将其创建为常量(使用匿名类)并使用该单个实例?我一直认为每次创建一个新实例没有任何好处,并且总是采用选项#2的方式(静态最终字段中的单个实例).
public class SomeClass {
//First option:
private static class SomeCustomComparator implements Comparator<SomeObject> {
public int compare(SomeObject o1, SomeObject o2) {
/*implementation*/
}
}
//Second option:
private static final Comparator<SomeObject> CUSTOM_COMPARATOR = new Comparator<SomeObject> {
public int compare(SomeObject o1, SomeObject o2) {
/*implementation*/
}
};
public void doSomething() {
//are there any advantages to one over the other?
SortedSet<SomeObject> s1 = new TreeSet<>(CUSTOM_COMPARATOR);
SortedSet<SomeObject> s2 = new TreeSet<>(new SomeCustomComparator());
}
}
Run Code Online (Sandbox Code Playgroud)
这里的假设是比较器中不需要保留任何状态.
如果doSomething()被调用很多怎么办?如果doSomething()从多个线程调用怎么办?如果将CUSTOM_COMPARATOR拉出到一个公共类并公开而不是私有,该怎么办?
| 归档时间: |
|
| 查看次数: |
1719 次 |
| 最近记录: |