在PHP中,您可以通过以下方式向数组中动态添加元素:
$x = new Array();
$x[] = 1;
$x[] = 2;
在此之后,$x
将是如下所示的数组:{1,2}
。
有没有办法在Java中做类似的事情?
发布于 2011-02-21 10:32:04
看看java.util.LinkedList或java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
发布于 2011-08-25 20:59:43
Apache Commons有一个ArrayUtils实现,可以在新数组的末尾添加一个元素:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
发布于 2011-02-21 10:34:01
您可以先使用ArrayList
,然后再使用toArray()
方法。但根据您所做的工作,您甚至可能根本不需要数组。看看Lists
是不是更符合你的需求。
https://stackoverflow.com/questions/5061721
复制相似问题