您的位置 首页 java

java 数组与List转换

  1. 数组是最简单数据结构,它的读写只能通过索引如读取scores[0]、写入scores[0]=1;而List底层虽然也是数组,但是其做了包装,提供了很好的api,如添加元素add、移除remove、读取get、判断是否存在contains等,功能更强大。List是 泛型 ,所以只能放引用类型,所以基本类型数组转成List是有点麻烦。需要先将基本类型转成引用类型。具体转换方法如下:
 int[] scores = new int[5];
for (int i = 0; i < scores.length; i++) {
    scores[i]=i;
}
System.out.println("==============================================");
for (int i = 0; i < scores.length; i++) {
    if(i==0){
        scores[i]=1;
    }
    System.out.println(scores[i]);
}  

基本类型数组转List

 ArrayList<Integer> arrayList = new ArrayList<>(scores.length);
Collections.addAll(arrayList, Arrays. Stream (scores).boxed().toArray(Integer[]::new));
arrayList.add(7);
arrayList.forEach(item->{
    System.out.println(item);
});  

引用类型转List:注意Arrays.asList只支持引用类型转换,因为入参为泛型

  Integer [] weight = new Integer[3];
List<Integer> integers = Arrays.asList(weight);  

通过Collections.addAll

 ArrayList<Integer> arrayList = new ArrayList<>(scores.length);
Collections.addAll(arrayList, Arrays.stream(scores).boxed().toArray(Integer[]::new));
arrayList.add(7);
arrayList.forEach(item->{
    System.out.println(item);
});  

通过Stream:

 List<Integer> collect = Arrays.stream(scores).boxed().collect(Collectors.toList());
collect.add(6);
collect.forEach(item->{
    System.out.println(item);
});  

文章来源:智云一二三科技

文章标题:java 数组与List转换

文章地址:https://www.zhihuclub.com/175514.shtml

关于作者: 智云科技

热门文章

评论已关闭

4条评论

  1. But as soon penis enlargement medicine dallas as he turned around, when Raj saw the boss, his expression changed immediately

  2. The Kidadl Team is made up of people from different walks of life, from different families and backgrounds, each with unique experiences and nuggets of wisdom to share with you But when the population of healthy types of bacteria decreases, it leaves room for others to settle in and cause problems Kairys, 2020

  3. Svensson PA, Englund MC, Snäckestrand MS, Hägg DA, Ohlsson BG, Stemme V, Mattsson Hulten L, Thelle DS, Fagerberg B, Wiklund O, Carlsson LM, Carlsson B

  4. Monitor Closely 1 metronidazole will increase the level or effect of lumateperone by affecting hepatic intestinal enzyme CYP3A4 metabolism Certain lifestyle risk factors can increase your risk of developing hemorrhoids including inadequate hydration, consuming a low fiber diet, or not getting enough exercise

网站地图