2012-10-25 46 views
11

使用自定義比較器,是否有每次實例化它的優點,而不是將其創建爲常量(使用匿名類)並使用該單一實例? 我一直認爲每次創建一個新實例都沒有好處,並且總是走過選項#2(靜態final字段中的單個實例)。比較器應該每次或僅一次實例化嗎?

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()); 
    } 
} 

這裏的假設是沒有狀態需要保存在比較器中。

如果doSomething()被調用了很多?如果doSomething()被多個線程調用會怎麼樣?如果CUSTOM_COMPARATOR被拉入普通班級並公開而不是私密?

回答

17

如果比較器沒有狀態(並且大多數不會),那麼創建單個實例並隨處使用它是絕對沒問題的。不要爲了它而創建額外的對象。

+0

只是爲了好奇 - 哪種比較器會有狀態? – climbage

+1

那麼,你可能有一個方法根據它的(不可變的)輸入創建一個'Comparator'。這本身並不完全是狀態,但是你需要爲不同的輸入構建不同的比較器。 –

+0

@climbage:我想*理論上*你可以有一個可以有不同模式的模式,當你想要的時候你可以改變模式。但它會很奇怪:) –