繁体   English   中英

将arraylist(整数)转换为整数数组

[英]converting an arraylist(integer) to an integer array

我已经尝试了很多东西来使这个代码工作,但事实并非如此。 我的目标是用数字{0, 1, 2, .... n-1}实例化nums[] nums没有大小,所以我使用了用零实例化nums列表。 请记住,结果必须是数组( nums )。

int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();

ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros 
//nums = listNum.toArray(nums);
for (int i =0; i < n; i++){
    nums[i] = i;
}

当你写这篇文章时:

ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros

listnum的大小为0,因此不会根据需要初始化nums


为什么不这样做:

nums = new int[n];

数组的大小是固定的。

 nums = new int[listNum.size()];

那永远不会奏效。 您正在使用零元素初始化数组。 一旦声明了数组大小,就无法更改它。

你在寻找什么

    int nums[] = {}; int n = 0;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the number:");
    n = scanner.nextInt();
    nums = new int[n];//instantiate nums with entered size
    for (int i =0; i < n; i++){
        nums[i] = i;
    }

因为你知道大小n ,所以摆脱那个ArrayList

您不需要ArrayList - 如果您从命令行获取n的输入,您可以使用它来初始化数组:

nums = new int[n];         
for (int i =0; i < n; i++){
    nums[i] = i;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM