在java中从int数组转换为Integer数组列表 [英] Converting from int array to Integer arraylist in java

查看:100
本文介绍了在java中从int数组转换为Integer数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从 Array 转换为 ArrayList 时遇到问题

I have a problem in converting from Array to ArrayList

public class one 
{
public static void main(String args[])
{
int y[]={12,25,38,46};
two p=new two();
p.setLocations(y);
}
}


import java.io.*;
import java.util.*;   

public class two 
{
    ArrayList<Integer> data_array=new ArrayList<Integer>();


void setLocations(int locations[])
{
        ArrayList<Integer> locations_arraylist=new ArrayList(Arrays.asList(locations));
        data_array=locations_arraylist;
    for(int i=0;i<data_array.size();i++)
        System.out.println("data_array["+i+"]="+data_array.get(i));
}
}

在下面一行

ArrayList<Integer> locations_arraylist=new  ArrayList(Arrays.asList(locations));
//Copying from array to ArrayList-Its converting,Please suggest

推荐答案

int[]List 完全不同.例如,Integer 有一个身份和一个值.没有非常简单的方法来进行转换.

An int[] is quite different from a List<Integer>. For example, an Integer has an identity as well as a value. There is no very simple way to do the conversion.

以下方式适用于 Java 8.

The following way works with Java 8.

int[] array = {1, 2, 3, 4, 5};
List<Integer> list = IntStream.of(array).boxed().collect(Collectors.toCollection(ArrayList::new));

以下方式适用于早期版本.

The following way works in earlier versions.

int[] array = {1, 2, 3, 4, 5};
List<Integer> list = new ArrayList<Integer>();
for (int a : array)
    list.add(a);

如果你将一个 int[] 传递给 Arrays.asList 你会得到一个 List,而不是一个 列表<整数>.

If you pass an int[] to Arrays.asList you get a List<int[]>, not a List<Integer>.

这篇关于在java中从int数组转换为Integer数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆