【问题标题】:converting an arraylist(integer) to an integer array将 arraylist(integer) 转换为整数数组
【发布时间】:2015-10-17 16:47:23
【问题描述】:

我已经尝试了一些方法来使这段代码正常工作,但没有成功。 我的目标是用数字{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;
}

【问题讨论】:

  • 在询问n 的值后,为什么不创建nums 呢?届时将知道大小。

标签: java arrays arraylist


【解决方案1】:

当你写这篇文章时:

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

listnum 的大小为 0,因此 nums 不会按照您的意愿进行初始化。


为什么不干呢:

nums = new int[n];

?

【讨论】:

  • 非常感谢,但这意味着我不需要创建 arraylist 。我只是想了解它是如何工作的。
【解决方案2】:

数组的大小是固定的。

 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;
    }

只要去掉那个 ArrayList,因为你知道大小 n

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 2015-08-06
      • 2019-08-24
      • 1970-01-01
      • 2011-09-18
      相关资源
      最近更新 更多