Java 如何向数组添加新元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2843366/
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
How to add new elements to an array?
提问by Pentium10
I have the following code:
我有以下代码:
String[] where;
where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
Those two appends are not compiling. How would that work correctly?
这两个附加没有编译。这将如何正确工作?
采纳答案by tangens
The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.
无法修改数组的大小。如果你想要一个更大的数组,你必须实例化一个新的。
A better solution would be to use an ArrayList
which can grow as you need it. The method ArrayList.toArray( T[] a )
gives you back your array if you need it in this form.
更好的解决方案是使用ArrayList
可以根据需要增长的 。ArrayList.toArray( T[] a )
如果您需要这种形式的数组,该方法会返回给您。
List<String> where = new ArrayList<String>();
where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );
If you need to convert it to a simple array...
如果您需要将其转换为一个简单的数组...
String[] simpleArray = new String[ where.size() ];
where.toArray( simpleArray );
But most things you do with an array you can do with this ArrayList, too:
但是你用数组做的大多数事情你也可以用这个 ArrayList 做:
// iterate over the array
for( String oneItem : where ) {
...
}
// get specific items
where.get( 1 );
回答by polygenelubricants
Use a List<String>
, such as an ArrayList<String>
. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).
使用List<String>
,例如ArrayList<String>
。它是动态增长的,与数组不同(参见:Effective Java 2nd Edition,Item 25: Prefer lists to arrays)。
import java.util.*;
//....
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
System.out.println(list); // prints "[1, 2, 3]"
If you insist on using arrays, you can use java.util.Arrays.copyOf
to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.
如果你坚持使用数组,你可以使用java.util.Arrays.copyOf
分配一个更大的数组来容纳额外的元素。不过,这确实不是最好的解决方案。
static <T> T[] append(T[] arr, T element) {
final int N = arr.length;
arr = Arrays.copyOf(arr, N + 1);
arr[N] = element;
return arr;
}
String[] arr = { "1", "2", "3" };
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
arr = append(arr, "4");
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"
This is O(N)
per append
. ArrayList
, on the other hand, has O(1)
amortized cost per operation.
这是O(N)
每append
. ArrayList
,另一方面,已O(1)
摊销每次操作的成本。
See also
也可以看看
- Java Tutorials/Arrays
- An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
- Java Tutorials/The List interface
- Java 教程/数组
- 数组是一个容器对象,它包含固定数量的单一类型的值。数组的长度是在创建数组时确定的。创建后,其长度是固定的。
- Java 教程/列表界面
回答by Simon
As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.
正如 tangens 所说,数组的大小是固定的。但是您必须先实例化它,否则它将只是一个空引用。
String[] where = new String[10];
This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a dynamically growing collection, use the ArrayList.
此数组只能包含 10 个元素。因此,您只能附加一个值 10 次。在您的代码中,您正在访问一个空引用。这就是为什么它不起作用。为了拥有动态增长的集合,请使用 ArrayList。
回答by npinti
I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size. You have to use an ArrayList or a Vector or any other dynamic structure.
我在 Java 方面经验不多,但我一直被告知数组是具有预定义大小的静态结构。您必须使用 ArrayList 或 Vector 或任何其他动态结构。
回答by Paligulus
You need to use a Collection List. You cannot re-dimension an array.
您需要使用集合列表。您不能重新调整数组的尺寸。
回答by Robert
There is no method append()
on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.
append()
数组没有方法。相反,正如已经建议的那样,List 对象可以满足动态插入元素的需要,例如。
List<String> where = new ArrayList<String>();
where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
Or if you are really keen to use an array:
或者,如果您真的很想使用数组:
String[] where = new String[]{
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
};
but then this is a fixed size and no elements can be added.
但这是一个固定大小,不能添加任何元素。
回答by RMachnik
If you would like to store your data in simple array like this
如果您想将数据存储在这样的简单数组中
String[] where = new String[10];
and you want to add some elements to it like numbers please us StringBuilder which is much more efficient than concatenating string.
并且您想向其中添加一些元素,例如数字,请使用 StringBuilder,这比连接字符串更有效。
StringBuilder phoneNumber = new StringBuilder();
phoneNumber.append("1");
phoneNumber.append("2");
where[0] = phoneNumber.toString();
This is much better method to build your string and store it into your 'where' array.
这是构建字符串并将其存储到“where”数组中的更好方法。
回答by ratzip
you can create a arraylist, and use Collection.addAll()
to convert the string array to your arraylist
您可以创建一个Collection.addAll()
数组列表,并用于将字符串数组转换为您的数组列表
回答by Jiao
Size of array cannot be modified. If you have to use an array, you can use:
数组的大小不能修改。如果必须使用数组,可以使用:
System.arraycopy(src, srcpos, dest, destpos, length);
回答by dforce
String[] source = new String[] { "a", "b", "c", "d" };
String[] destination = new String[source.length + 2];
destination[0] = "/bin/sh";
destination[1] = "-c";
System.arraycopy(source, 0, destination, 2, source.length);
for (String parts : destination) {
System.out.println(parts);
}