Java动态数组大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1647260/
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
Java dynamic array sizes?
提问by Paul
I have a class - xClass, that I want to load into an array of xClass so I the declaration:
我有一个类 - xClass,我想加载到一个 xClass 数组中,所以我声明:
xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();
However, I don't know if I will need 10. I may need 8 or 12 or any other number for that matter. I won't know until runtime. Can I change the number of elements in an array on the fly? If so, how?
但是,我不知道我是否需要 10。我可能需要 8 或 12 或任何其他数字。直到运行时我才知道。我可以动态更改数组中的元素数量吗?如果是这样,如何?
采纳答案by cletus
No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:
不,一旦创建,您就无法更改数组的大小。您要么必须分配比您认为需要的更大的它,要么接受必须重新分配它需要增加大小的开销。当它发生时,您必须分配一个新数据并将数据从旧数据复制到新数据:
int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;
If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList
essentially wraps an array and takes care of the logic for growing the array as required:
如果您发现自己处于这种情况,我强烈建议您改用 Java 集合。特别是ArrayList
本质上包装一个数组并根据需要处理增长数组的逻辑:
List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());
Generally an ArrayList
is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:
通常ArrayList
,出于多种原因, an 无论如何都是数组的首选解决方案。一方面,数组是可变的。如果你有一个这样做的类:
class Myclass {
private int[] items;
public int[] getItems() {
return items;
}
}
you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:
您已经创建了一个问题,因为调用者可以更改您的私有数据成员,这会导致各种防御性复制。将此与 List 版本进行比较:
class Myclass {
private List<Integer> items;
public List<Integer> getItems() {
return Collections.unmodifiableList(items);
}
}
回答by newacct
You set the number of elements to anything you want at the time you create it:
您可以在创建时将元素数量设置为您想要的任何内容:
xClass[] mysclass = new xClass[n];
Then you can initialize the elements in a loop. I am guessing that this is what you need.
然后您可以在循环中初始化元素。我猜这就是你所需要的。
If you need to add or remove elements to the array after you create it, then you would have to use an ArrayList
.
如果在创建数组后需要向数组添加或删除元素,则必须使用ArrayList
.
回答by Amir Afghani
Where you declare the myclass[] array as :
您将 myclass[] 数组声明为:
xClass myclass[] = new xClass[10]
, simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.
,只需将您需要的 XClass 元素的数量作为参数传入。那时你知道你需要多少吗?通过将数组声明为具有 10 个元素,您并不是在声明 10 个 XClass 对象,您只是创建了一个包含 10 个 xClass 类型元素的数组。
回答by Jé Queue
Yes, wrap it and use the Collections framework.
是的,包装它并使用集合框架。
List l = new ArrayList();
l.add(new xClass());
// do stuff
l.add(new xClass());
Then use List.toArray() when necessary, or just iterate over said List.
然后在必要时使用 List.toArray() ,或者只是迭代所述列表。
回答by Stephen C
As others have said, you cannot change the size of an existing Java array.
正如其他人所说,您不能更改现有 Java 数组的大小。
ArrayList is the closest that standard Java has to a dynamic sized array. However, there are some things about ArrayList (actually the List interface) that are not "array like". For example:
ArrayList 是标准 Java 中最接近动态大小数组的。但是,ArrayList(实际上是 List 接口)有些东西不是“类似数组”的。例如:
- You cannot use
[ ... ]
to index a list. You have to use theget(int)
andset(int, E)
methods. - An ArrayList is created with zero elements. You cannot simple create an ArrayList with 20 elements and then call
set(15, foo)
. - You cannot directly change the size of an ArrayList. You do it indirectly using the various
add
,insert
andremove
methods.
- 您不能用于
[ ... ]
索引列表。您必须使用get(int)
和set(int, E)
方法。 - ArrayList 是用零个元素创建的。您不能简单地创建一个包含 20 个元素的 ArrayList 然后调用
set(15, foo)
. - 您不能直接更改 ArrayList 的大小。您可以使用各种
add
,insert
和remove
方法间接地做到这一点。
If you want something more array-like, you will need to design your own API. (Maybe someone could chime in with an existing third party library ... I couldn't find one with 2 minutes "research" using Google :-) )
如果你想要更像数组的东西,你需要设计你自己的 API。(也许有人可以加入现有的第三方库......我找不到使用 Google 进行 2 分钟“研究”的库 :-))
If you only really need an array that grows as you are initializing it, then the solution is something like this.
如果你真的只需要一个随着你初始化它而增长的数组,那么解决方案就是这样。
ArrayList<T> tmp = new ArrayList<T>();
while (...) {
tmp.add(new T(...));
}
// This creates a new array and copies the element of 'tmp' to it.
T[] array = tmp.toArray(new T[tmp.size()]);
回答by OscarRyz
In java array length is fixed.
在java中数组长度是固定的。
You can use a List to hold the values and invoke the toArray
method if needed
See the following sample:
您可以使用 List 来保存值并在toArray
需要时调用该方法 请参阅以下示例:
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class A {
public static void main( String [] args ) {
// dynamically hold the instances
List<xClass> list = new ArrayList<xClass>();
// fill it with a random number between 0 and 100
int elements = new Random().nextInt(100);
for( int i = 0 ; i < elements ; i++ ) {
list.add( new xClass() );
}
// convert it to array
xClass [] array = list.toArray( new xClass[ list.size() ] );
System.out.println( "size of array = " + array.length );
}
}
class xClass {}
回答by sinuhepop
As other users say, you probably need an implementation of java.util.List.
正如其他用户所说,您可能需要 java.util.List 的实现。
If, for some reason, you finally need an array, you can do two things:
如果由于某种原因,你最终需要一个数组,你可以做两件事:
Use a List and then convert it to an array with myList.toArray()
Use an array of certain size. If you need more or less size, you can modify it with java.util.Arrays methods.
使用列表,然后使用 myList.toArray() 将其转换为数组
使用特定大小的数组。如果您需要更多或更少的大小,您可以使用 java.util.Arrays 方法修改它。
Best solution will depend on your problem ;)
最佳解决方案将取决于您的问题;)
回答by Shashank Raghunath
I recommend using vectors instead. Very easy to use and has many predefined methods for implementation.
我建议改用向量。非常易于使用,并有许多预定义的实现方法。
import java.util.*;
Vector<Integer> v=new Vector<Integer>(5,2);
to add an element simply use:
添加元素只需使用:
v.addElement(int);
In the (5,2)the first 5 is the initial size of the vector. If you exceed the initial size,the vector will grow by 2 places. If it exceeds again, then it will again increase by 2 places and so on.
在(5,2) 中,前 5 是向量的初始大小。如果超过初始大小,向量将增长 2 位。如果再次超过,则再次增加2位,以此类推。
回答by man.2067067
回答by Pascal9x
You can use ArrayList:
您可以使用 ArrayList:
import java.util.ArrayList;
import java.util.Iterator;
...
...
ArrayList<String> arr = new ArrayList<String>();
arr.add("neo");
arr.add("morpheus");
arr.add("trinity");
Iterator<String> foreach = arr.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());