rel*_*abe 5 java generics collections
Set<Integer> iset = new HashSet<>();
iset.add(1);
List<Integer> ilist = Arrays.asList(iset);
Run Code Online (Sandbox Code Playgroud)
我的意图是将整数集转换为整数列表,但编译器抱怨 List> 无法转换为 List。为什么 asList 以这种方式工作以及何时使用它?将 Set 转换为 List 的正确方法是什么?
Ekl*_*vya 10
因为仅Arrays.asList将其iset视为一种元素。这就是为什么这会创建List<Set<Integer>>.
要制作集合中元素的列表,请将集合传递给列表的构造函数。
List<Integer> ilist = new ArrayList<Integer>(iset);
Run Code Online (Sandbox Code Playgroud)
的不同用途Arrays.asList:
List<Integer> ilist1 = Arrays.asList(1); // Single element
List<Integer> ilist2 = Arrays.asList(1,2,3); // Multiple element
Integer a[] = new Integer[] { 10, 20, 30, 40 };
List<Integer> ilist3 = Arrays.asList(a); // Array
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
420 次 |
| 最近记录: |