更轻松地覆盖给定实例上的compareTo方法

时间:2012-05-31 09:48:20

标签: java inheritance override anonymous

对我来说,一些外部函数给了我一个java.io.File实例,但我想在运行时更改该实例的compareTo的默认行为。什么是最好的方法?

我唯一能想到的就是将这个File实例包装到

public class FileWrapper extends File{   

    FileWrapper(File in){
        //Assign var to the global var      
    }

    @Overrides
    public compareTo(File in){ return whatever;}

}

并使所有方法都覆盖File的方法并将调用转发给通过构造函数填充的全局包装实例,但这非常难看......

也许我忘了其他一些更简单的方法......

1 个答案:

答案 0 :(得分:3)

您可能想要使用compareTo方法的唯一原因是对集合进行排序。

您始终可以创建Comparator并将其传递给Collections.sort来电。

Collections.sort(myList, new Comparator<File>() {
    public int compare(File file1, File file2) {
        // write your custom compare logic here.
    }
});

即使您使用排序集合(例如TreeSet),它也已经为您提供了重载的构造函数,用于传入Comparator

/**
 * Constructs a new, empty tree set, sorted according to the specified
 * comparator.  All elements inserted into the set must be <i>mutually
 * comparable</i> by the specified comparator: {@code comparator.compare(e1,
 * e2)} must not throw a {@code ClassCastException} for any elements
 * {@code e1} and {@code e2} in the set.  If the user attempts to add
 * an element to the set that violates this constraint, the
 * {@code add} call will throw a {@code ClassCastException}.
 *
 * @param comparator the comparator that will be used to order this set.
 *        If {@code null}, the {@linkplain Comparable natural
 *        ordering} of the elements will be used.
 */
public TreeSet(Comparator<? super E> comparator) {
    this(new TreeMap<E,Object>(comparator));
}