一.数组转换为List或ArrayList
1.String类型数组转换为ArrayList
public void test(){
String[] str = {"first","second","third"};
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(str));
}
asList(T):返回由指定数组支持的固定大小的列表。
2.int类型数组转换为List
public void test(){
int[] nums = {5,6,8,4,7,3};
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
}
- Arrays.stream将 int[] 转换成 IntStream.
- 使用IntStream.boxed()进行装箱,将IntStream转换成Stream.
- Stream.collect()将Stream转换成List,得到List.
二.List转换为数组
toArray()方法
public void test(){
List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
String[] str1 = list.toArray(new String[list.size()]);
}
三.Iterator遍历List
public void test(){
List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
for(Iterator<String> i = list.iterator(); i.hasNext();){
String str = i.next();
System.out.println(str);
}
}
- hasNext():如果迭代具有更多的元素,则返回true 。用于判定List是否还有元素,有则返回true,继续迭代。
- next():返回迭代中的下一个元素。用来获取元素。