2012-05-31 58 views
0

对我而言,一些外部函数给了我一个java.io.File实例,但是我想要为该实例即时更改compareTo的默认行为。最好的方法是什么?更容易的方法来覆盖给定实例上的compareTo方法

我能想到的唯一的事情就是这个包裹File实例为

public class FileWrapper extends File{ 

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

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

} 

,使所有方法重写File's那些和着通过构造pased全球包装实例的调用,但it'希望能非常难看......

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

+0

什么是Java中的匿名*函数? – adarshr

+0

对不起,我的意思是一个匿名类中的函数 – Whimusical

+1

我不确定这会以任何方式工作。 'compareTo'必须是可交换的:'File.compareTo(FileWrapper)'必须与'FileWrapper.compareTo(File)'对称,但不能控制'File.compareTo(FileWrapper)'。 –

回答

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)); 
} 
+0

你完全猜到了!谢谢!! – Whimusical

+0

是否有与equals相似的东西?一个Equalizator或什么?想象一下相同的情况,但想要覆盖等于,因为它必须与compareTo – Whimusical

+0

一致。不可以。 – adarshr