kam*_*lot 80 java arrays dynamic-arrays
在PHP中,您可以通过以下方式动态向元数添加元素:
$x = new Array();
$x[] = 1;
$x[] = 2;
Run Code Online (Sandbox Code Playgroud)
在此之后,$x将是这样的数组:{1,2}.
有没有办法在Java中做类似的事情?
cor*_*iKa 108
查看java.util.LinkedList或java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Run Code Online (Sandbox Code Playgroud)
Paŭ*_*ann 64
Java中的数组具有固定的大小,因此您不能像在PHP中那样"在末尾添加内容".
有点类似于PHP的行为是这样的:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以写:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
Run Code Online (Sandbox Code Playgroud)
但是这种方案对于较大的阵列来说非常低效,因为它每次都会复制整个阵列.(事实上它并不完全等同于PHP,因为你的旧数组保持不变).
PHP数组实际上与添加了"max key"的Java HashMap完全相同,因此它将知道下一个使用哪个键,以及奇怪的迭代顺序(以及Integer键和某些字符串之间的奇怪等价关系).但是对于简单的索引集合,最好在Java中使用List,就像其他的回答者一样.
如果List由于在Integer中包装每个int的开销而要避免使用,请考虑对基本类型使用集合的重新实现,这些类型在内部使用数组,但只有在内部数组已满时才会对每次更改执行复制(就像ArrayList).(一个快速搜索的示例是这个IntList类.)
番石榴含有制造这种包装方法中Ints.asList,Longs.asList等等.
mis*_*ist 19
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)
Run Code Online (Sandbox Code Playgroud)
Sal*_*ara 12
我经常在网上看到这个问题,在我看来,许多声誉很高的人没有正确回答这些问题.所以我想在这里表达我自己的答案.
首先,我们应该考虑和之间存在差异.arrayarraylist
该问题要求向数组添加元素,而不是ArrayList
答案很简单.它可以分3个步骤完成.
最后这里是代码:
步骤1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Run Code Online (Sandbox Code Playgroud)
第2步:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Run Code Online (Sandbox Code Playgroud)
第3步:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Run Code Online (Sandbox Code Playgroud)
第4步
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
Run Code Online (Sandbox Code Playgroud)