java中的动态数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21643081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic array in java
提问by Daksh Shah
What i am trying to do is
我想做的是
...
int sum[];
...
for(int z.....){
...
sum[z] = some_random_value;
...
}
But it gives an error at line sum[z]=ran;that variable summight not have been initialized.
但是它在sum[z]=ran;变量sum可能尚未初始化的行给出错误。
I tried int sum[] = 0;instead of int sum[];but even that gave an error.
(I am basically a C programmer)
我试过int sum[] = 0;而不是,int sum[];但即使这样也出错了。(我基本上是一个 C 程序员)
采纳答案by Makoto
An array of dynamic size isn't possible in Java - you have to either know the size before you declare it, or do resizing operations on the array (which can be painful).
动态大小的数组在 Java 中是不可能的 - 您必须在声明之前知道大小,或者对数组进行调整大小的操作(这可能很痛苦)。
Instead, use an ArrayList<Integer>, and if you need it as an array, you can convert it back.
相反,使用ArrayList<Integer>, 如果您需要将其作为数组,则可以将其转换回来。
List<Integer> sum = new ArrayList<>();
for(int i = 0; i < upperBound; i++) {
sum.add(i);
}
// necessary to convert back to Integer[]
Integer[] sumArray = sum.toArray(new Integer[0]);
回答by Juvanis
This is for getting rid of compile-time error:
这是为了摆脱编译时错误:
int sum[] = null;
However, to prevent runtime-errorsI strongly suggest you to initialize your array like this:
但是,为了防止运行时错误,我强烈建议您像这样初始化数组:
int[] sum = new int[10];
The number in brackets denotes the array size.
括号中的数字表示数组大小。
And if your size is dynamic, then use a Listimplementation, such as ArrayList.
如果您的大小是动态的,则使用List实现,例如ArrayList.
回答by Suresh Atta
int sum[]= new int[length];
You haven't initialized. As of now , you just declared.
你还没有初始化。截至目前,您刚刚宣布。
And do not for get that the lengthof the arrayshould decide at the time of initialization.
不要对获取的length的array应在初始化时决定。
Even if you do int sum[] = null;you'll end up with an NullPointerExceptionwhile you do sum[z]=ran;
即使你做 intsum[] = null;你最终也会有一段NullPointerException时间 sum[z]=ran;
Can't i just keep it dynamic? the length is variable
我不能让它保持动态吗?长度是可变的
No. Arrays lenght should be fixed while initializing it. Look into Collection's in java. More specifically A Listinterface with ArrayListimplementation, which is
不。数组长度应该在初始化时固定。在java中查看Collection。更具体地说,List具有ArrayList实现的接口,即
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.
List 接口的可调整大小的数组实现。实现所有可选的列表操作,并允许所有元素,包括 null。
By writing int[] anArray = new int[10];you are telling that
通过写作,int[] anArray = new int[10];你是在告诉
Allocate an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
为 10 个整数元素分配一个具有足够内存的数组,并将该数组分配给 anArray 变量。
Seems you are new to array's and even for java. The tutorial may help you better to understand. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
似乎您是数组的新手,甚至是 Java 的新手。本教程可能会帮助您更好地理解。 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
回答by Makoto
If you're talking about dynamic arrays, the class can be represented as -
如果您在谈论动态数组,则该类可以表示为 -
public class DynArray {
private int size; // The current size of the array (number of elements in the array)
private int maxSize; // Size of memory allocated for the array
private Object[] array; // size of array == maxSize
/**
* An array constructor
* Argument specifies how much memory is needed to allocate for elements
*
* @param sz
* @throws IndexOutOfBoundsException
*/
public DynArray(int sz) throws IndexOutOfBoundsException {
// Here called another more general constructor
this(sz, sz, null);
}
/**
* Call the constructor, in which indicated how much memory is allocated
* for the elements and how much memory is allocated total.
*
* @param sz
* @param maxSz
* @throws IndexOutOfBoundsException
*/
public DynArray(int sz, int maxSz) throws IndexOutOfBoundsException {
// Here called another more general constructor
this(sz, maxSz, null);
}
/**
* Additional argument contains an array of elements for initialization
*
* @param sz
* @param maxSz
* @param iniArray
* @throws IndexOutOfBoundsException
*/
public DynArray(int sz, int maxSz, Object[] iniArray) throws IndexOutOfBoundsException {
if((size = sz) < 0) {
throw new IndexOutOfBoundsException("Negative size: " + sz);
}
maxSize = (maxSz < sz ? sz : maxSz);
array = new Object[maxSize]; // memory allocation
if(iniArray != null) { // copying items
for(int i = 0; i < size && i < iniArray.length; i++) {
array[i] = iniArray[i];
// Here it was possible to use the standard method System.arraycopy
}
}
}
/**
* Indexing
*
* @param i
* @return
* @throws IndexOutOfBoundsException
*/
public Object elementAt(int i) throws IndexOutOfBoundsException {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("Index" + i +
" out of range [0," + (size - 1) + "]");
}
return array[i];
}
/**
* Changing the current size of the array. argument delta specifies
* direction of change (positive - increase the size;
* negative - decrease the size)
*
* @param delta
*/
public void resize(int delta) {
if (delta > 0) enlarge(delta); // increasing the size of the array
else if (delta < 0) shrink(-delta); // decreasing the size of the array
}
/**
* Increasing the size of the array
*
* @param delta
*/
public void enlarge(int delta) {
if((size += delta) > maxSize) {
maxSize = size;
Object[] newArray = new Object[maxSize];
// copying elements
for(int i =0; i < size - delta; i++)
newArray[i] = array[i];
array = newArray;
}
}
/**
* Decreasing the size of the array
*
* @param delta
*/
public void shrink(int delta) {
size = (delta > size ? 0 : size - delta);
}
/**
* Adding a new element
* (with a possible increasing the size of the array)
*
* @param e
*/
public void add(Object e) {
resize(1);
array[size-1] = e;
}
/**
* Removing the given value - shifting elements and subsequent
* reduction the size of the array
*
* @param e
*/
public void remove(Object e) {
int j;
for(j = 0; j < size; j++) {
if(e.equals(array[j])) {
break;
}
}
if(j == size) {
return false;
} else {
for(int k = j; k < size; k++)
array[k] = array[k + 1];
resize(-1);
return true;
}
}
}
回答by Krease
You still need to initializeyour array after it's declared: int sum[]= new int[length];.
在声明数组后,您仍然需要对其进行初始化:int sum[]= new int[length];。
Now you can assign values in the array up to the size specified when you initialized it.
现在,您可以将数组中的值分配到初始化时指定的大小。
If you want to have a dynamically sized array, use ArrayListand call toArrayat the end to convert it back to a regular array.
如果您想要一个动态大小的数组,ArrayList请toArray在最后使用并调用将其转换回常规数组。

