2011-03-16 35 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

相关问题