2014-02-26 67 views
0

我有不同類型的對象的LinkedHashSets從一個Java類傳遞到另一個,我是否將它們打包在一個更大的對象中(如果可能的話,還有另一個鏈接的哈希集),或者我只是以正常方式傳遞它們作爲參數?我可以擁有LinkedHashSets的LinkedHashSet嗎?

回答

1

兩者都是可能的。

如果包裝LinkedHashSet s轉換爲其他LinkedHashSet你可能失去類型信息LinkedHashSet<LinkedHashSet<?>>是收集各種LinkedHashSet S IN一個地方的唯一途徑。您也可以查看HashMap,因爲您通常會嘗試訪問特定的子LinkedHashSet;通過在常見的類或接口中定義常量查找鍵,使用映射可以輕鬆實現。

如果在類之間始終存在相同的LinkedHashSet,參數或參數對象通常是更好的解決方案,因爲它們提供類型信息。一個參數對象的類可能看起來像這樣

public class Parameters { 
    private LinkedHashSet<String> namesSet = null; 
    private LinkedHashSet<Locale> localesSet = null; 

    public Parameters(LinkedHashSet<String> namesSet, LinkedHashSet<Locale> localesSet) { 
     this.namesSet = namesSet; 
     this.localesSet = localesSet; 
    } 

    public Parameters() { 
    } 

    public LinkedHashSet<String> getNamesSet() { 
     return namesSet; 
    } 

    public void setNamesSet(LinkedHashSet<String> namesSet) { 
     this.namesSet = namesSet; 
    } 

    public LinkedHashSet<Locale> getLocalesSet() { 
     return localesSet; 
    } 

    public void setLocalesSet(LinkedHashSet<Locale> localesSet) { 
     this.localesSet = localesSet; 
    } 
} 

參數對象的優點是它們保持方法簽名短,可以傳遞;在通過併發線程修改這些對象時要小心;-)。

+1

我採用了參數類解決方案:) –

1

是的。例如:

LinkedHashSet<LinkedHashSet<String>> 
+0

但它們並不都是LinkedHashSet - 其中一些是LinkedHashSet 其他的是LinkedHashSet 等等。 –

+0

如果你有一個共同的超類或接口,你總是可以使用Object或其他類。 – JustinKSU

相關問題