2016-01-11 29 views
-3

我编写了下面的方法来我的ArrayList转换成一组:方法一个ArrayList转换成一组

public static Set<Animal> toSet(){ 
    Set<Animal> aniSet = new HashSet<Animal>(animals); 
    return aniSet; 
} 

我想这样做,而不是:

public static Set<Animal> toSet(){ 
    return HashSet<Animal>(animals); 
} 

为什么我得到一个错误消息说它找不到变量HashSet?我需要先存储变量吗?

编辑:必须在我的Hashset之前添加新的。编码让我觉得很愚蠢:')

+9

你忘了'新'' – Eran

+4

以及'动物'必须来自某个地方的事实。 –

回答

3

有两个问题与此代码:

  1. 你忘了animals必须来自某个地方;我不认为第一个例子也可以编译;和
  2. 您在创建新的HashSet<Animal>时忘记使用new

这可能是预期的行为:

public static <T> Set<T> toSet(Collection<? extends T> data){ 
    return new HashSet<T>(data); 
} 

然后,您可以与调用它:

ArrayList<Animal> animals = new ArrayList<>(); 
//do something with the animals list 
//... 

Set<Animal> theSet = Foo.<Animal>toSet(animals); 

用通用的静态方法,你可以用你喜欢的任何类型的呼叫。通过使用Collection<? extends T>,您不仅限于ArrayList<T>,但您可以使用任何种类的CollectionLinkedList,HashSet,TreeSet,...)。最后,该集合的类型甚至不必是动物。您可以将ArrayList<Cat>转换为HashSet<Animal>

但请注意,此方法没有太多用处:调用它并不比直接使用构造函数短得多。我看到的唯一真正的优点是,您将封装为其中Set<T>即将使用,因此如果您稍后改变主意为TreeSet<T>所有调用此方法的方法将生成TreeSet<T>而不是HashSet<T>

相关问题