Java:如果未知,我如何初始化数组大小? [英] Java: how do i initialize an array size if it's unknown?

查看:217
本文介绍了Java:如果未知,我如何初始化数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求用户输入1到100之间的一些数字并将它们分配到一个数组中。数组大小未初始化,因为它取决于用户输入数字的次数。
我应该如何分配数组长度?
如果用户输入5 6 7 8 9(5个数字),那么

I'm asking the user to enter some numbers between 1 and 100 and assign them into an array. The array size is not initialized since it is dependent on the number of times the user enters a number. How should i assign the array length?? If user enters 5 6 7 8 9 (5 numbers), then

int[] list;  

变为

int[] list = new int[5];

我正在尝试使用循环,但它不会停止。

I'm trying to use a loop, but it won't stop.

int[] integers;
int j = 0;
do {
       integers = new int[j + 1];
       integers[j] = in.nextInt(); 
       j++;      
} while((integers[j-1] >= 1) ||(integers[j-1]) <= 100);


推荐答案

你应该使用 列出 像这样,不是数组。作为一般经验法则,当您不知道将在手数中添加多少元素时,请使用 List 。大多数人可能会使用 <$ c $解决此问题c> ArrayList

You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.

如果你真的不能使用 List ,那么你可能不得不使用一些初始大小的数组(可能是10?)并跟踪你的数组容量与你要添加的元素数量,并将元素复制到一个新的更大的数组中用完房间(这基本上是 ArrayList 在内部完成)。另请注意,在现实世界中,您将从不这样做 - 您将使用专门为此类情况制作的标准类之一,例如 ArrayList

If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.

这篇关于Java:如果未知,我如何初始化数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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