2011-03-16 82 views

回答

23

List.addAllSet.addAll

5
public static <E> Set<E> getSetForList(List<E> lst){ 
    return new HashSet<E>(lst);//assuming you don't care for duplicate entry scenario :) 
} 

public static <E> List<E> getListForSet(Set<E> set){ 
    return new ArrayList<E>(set);// You can select any implementation of List depending on your scenario 
} 
7

大多數類java collection framework的有一個構造函數,考慮元素的集合作爲參數。您應該使用您喜歡的實現噸做轉換爲exameple(與HashSetArrayList):

public class MyCollecUtils { 

    public static <E> Set<E> toSet(List<E> l) { 
     return new HashSet<E>(l); 
    } 

    public static <E> List<E> toSet(Set<E> s) { 
     return new ArrayList<E>(s); 
    } 
} 
+1

正如你已經提到的:大多數採取收集作爲他們的C - tor的參數。那麼爲什麼不使用它:'toSet(Collection c)'和'toSet(Collection c)'? – 2011-03-16 09:10:28

+0

在一般情況下,實際上,你甚至不會爲它構建函數,只是使用構造函數。正如我們在一個特定的情況下,問題是從列表轉換爲集合,反之亦然,我更喜歡指定參加集合的類型。 – Nicolas 2011-03-16 09:13:10

+0

這段代碼非常簡單和基本,可能根本不值得一個函數。 Util.toSet(col)並不比新的HashSet (col)更好。然後,您可以選擇您的類的實際實現,並可以從任何集合類型轉換爲任何其他類型。 – 2011-03-16 09:18:09

4

一個函數,而不是您可以有兩個函數來實現這個功能:

// Set to List 
public List setToList(Set set) { 
    return new ArrayList(set); 
} 

// List to Set 
public Set listToSet(List list) { 
    return new HashSet(list); 
} 

在單功能:

public Collection convertSetList(Collection obj) { 
    if (obj instanceof java.util.List) { 
     return new HashSet((List)obj); 
    } else if(obj instanceof java.util.Set) { 
     return new ArrayList((Set)obj); 
    }  
    return null; 
} 

實施例:(更新)

public class Main { 
    public static void main(String[] args) { 
     Set s = new HashSet(); 
     List l = new ArrayList(); 

     s.add("1");s.add("2");s.add("3"); 
     l.add("a");l.add("b");l.add("c"); 

     Collection c1 = convertSetList(s); 
     Collection c2 = convertSetList(l); 

     System.out.println("c1 type is : "+ c1.getClass()); 
     System.out.println("c2 type is : "+ c2.getClass());   
    } 

    public static Collection convertSetList(Collection obj) { 
     if (obj instanceof java.util.List) { 
      System.out.println("List!"); 
      return (Set)new HashSet((List) obj); 
     } else if (obj instanceof java.util.Set) { 
      System.out.println("Set!"); 
      return (List)new ArrayList((Set) obj); 
     } else { 
      System.out.println("Unknow type!"); 
      return null; 
     } 
    } 
} 
+0

謝謝,我刪除了我的-1,但我仍然認爲這樣做不像你在'convertSetList'中建議的那樣明智:因爲既沒有返回List或Set,也沒有返回Collection。如果需要引用「List」或「Set」,則需要進行一些轉換。另外,當傳遞'List'或者'Set'以外的東西時,返回'null'(不好,IMO)。最後,你的代碼中仍然沒有泛型的使用,使得它的Java 1.4.2代碼(從很久以前!):) – 2011-03-16 09:26:31

+0

上面的一段代碼爲我工作。根據用戶的需求他想要一個功能。很顯然,他需要演員或做一些驗證。那就是爲什麼這樣寫。糾正我,如果我錯了。謝謝。 – 2011-03-16 09:44:40

相關問題