将 Arraylist 转换为 Set 的方法
Method to convert an Arraylist into a Set
我编写了以下方法将我的 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?我需要先存储一个变量吗?
编辑:必须在我的哈希集之前添加新的。编码让我觉得自己很笨:')
这段代码有两个问题:
- 你忘了
animals
必须来自某个地方;我也不认为第一个示例可以编译;和
- 您在创建新
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>
,还可以使用任何类型的 Collection
(LinkedList
、HashSet
、TreeSet
,...)。最后,该集合的类型甚至不必是动物。您可以将 ArrayList<Cat>
转换为 HashSet<Animal>
.
但是请注意,此方法没有太多用处:调用它并不比直接使用构造函数短多少。我看到的唯一真正的优势是你封装你将要使用的Set<T>
,这样如果你以后改变主意TreeSet<T>
所有调用这个的方法toSet
方法将生成 TreeSet<T>
而不是 HashSet<T>
.
我编写了以下方法将我的 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?我需要先存储一个变量吗?
编辑:必须在我的哈希集之前添加新的。编码让我觉得自己很笨:')
这段代码有两个问题:
- 你忘了
animals
必须来自某个地方;我也不认为第一个示例可以编译;和 - 您在创建新
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>
,还可以使用任何类型的 Collection
(LinkedList
、HashSet
、TreeSet
,...)。最后,该集合的类型甚至不必是动物。您可以将 ArrayList<Cat>
转换为 HashSet<Animal>
.
但是请注意,此方法没有太多用处:调用它并不比直接使用构造函数短多少。我看到的唯一真正的优势是你封装你将要使用的Set<T>
,这样如果你以后改变主意TreeSet<T>
所有调用这个的方法toSet
方法将生成 TreeSet<T>
而不是 HashSet<T>
.