2012-05-31 85 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