简体   繁体   English

如何向数组添加新元素?

[英]How to add new elements to an array?

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?这将如何正确工作?

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.更好的解决方案是使用可以根据需要增长的ArrayList The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.如果您需要这种形式的数组,方法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 );

Use aList<String> , such as an ArrayList<String> .使用List<String> ,例如ArrayList<String> It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays ).它是动态增长的,与数组不同(参见: 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.如果你坚持使用数组,你可以使用java.util.Arrays.copyOf分配一个更大的数组来容纳额外的元素。 This is really not the best solution, though.不过,这确实不是最好的解决方案。

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 .这是O(N)每个append ArrayList , on the other hand, has O(1) amortized cost per operation.另一方面, ArrayList每个操作的摊销成本为O(1)

See also也可以看看

Apache Commons Lang has Apache Commons Lang 有

T[] t = ArrayUtils.add( initialArray, newitem );

it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.它返回一个新数组,但如果您出于某种原因确实在使用数组,这可能是执行此操作的理想方法。

There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.还有一个我在这里没有看到的选项,它不涉及“复杂”的对象或集合。

String[] array1 = new String[]{"one", "two"};
String[] array2 = new String[]{"three"};
String[] array = new String[array1.length + array2.length];
System.arraycopy(array1, 0, array, 0, array1.length);
System.arraycopy(array2, 0, array, array1.length, array2.length);

There is no method append() on arrays.数组上没有append()方法。 Instead as already suggested a List object can service the need for dynamically inserting elements eg.相反,正如已经建议的那样,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.但这是一个固定大小,不能添加任何元素。

As tangens said, the size of an array is fixed.正如 tangens 所说,数组的大小是固定的。 But you have to instantiate it first, else it will be only a null reference.但是您必须先实例化它,否则它将只是一个空引用。

String[] where = new String[10];

This array can contain only 10 elements.此数组只能包含 10 个元素。 So you can append a value only 10 times.因此,您只能附加一个值 10 次。 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.为了拥有动态增长的集合,请使用 ArrayList。

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);
}

I've made this code!我已经制作了这个代码! It works like a charm!它就像一个魅力!

public String[] AddToStringArray(String[] oldArray, String newString)
{
    String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
    newArray[oldArray.length] = newString;
    return newArray;
}

I hope you like it!!我希望你喜欢它!!

You need to use a Collection List.您需要使用集合列表。 You cannot re-dimension an array.您不能重新调整数组的尺寸。

Adding new items to String array.向字符串数组添加新项目。

String[] myArray = new String[] {"x", "y"};

// Convert array to list
List<String> listFromArray = Arrays.asList(myArray);

// Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
List<String> tempList = new ArrayList<String>(listFromArray);
tempList.add("z");

//Convert list back to array
String[] tempArray = new String[tempList.size()];
myArray = tempList.toArray(tempArray);

There are many ways to add an element to an array.有很多方法可以将元素添加到数组中。 You can use a temp List to manage the element and then convert it back to Array or you can use the java.util.Arrays.copyOf and combine it with generics for better results.您可以使用临时List来管理元素,然后将其转换回Array或者您可以使用java.util.Arrays.copyOf并将其与泛型结合以获得更好的结果。

This example will show you how:此示例将向您展示如何:

public static <T> T[] append2Array(T[] elements, T element)
{
    T[] newArray = Arrays.copyOf(elements, elements.length + 1);
    newArray[elements.length] = element;

    return newArray;
}

To use this method you just need to call it like this:要使用此方法,您只需像这样调用它:

String[] numbers = new String[]{"one", "two", "three"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(numbers, "four");
System.out.println(Arrays.toString(numbers));

If you want to merge two array you can modify the previous method like this:如果要合并两个数组,可以像这样修改以前的方法:

public static <T> T[] append2Array(T[] elements, T[] newElements)
{
    T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
    System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);

    return newArray;
}

Now you can call the method like this:现在您可以像这样调用该方法:

String[] numbers = new String[]{"one", "two", "three"};
String[] moreNumbers = new String[]{"four", "five", "six"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(numbers, moreNumbers);
System.out.println(Arrays.toString(numbers));

As I mentioned, you also may use List objects.正如我提到的,您也可以使用List对象。 However, it will require a little hack to cast it safe like this:但是,它需要一点技巧才能像这样安全地投射它:

public static <T> T[] append2Array(Class<T[]> clazz, List<T> elements, T element)
{
    elements.add(element);
    return clazz.cast(elements.toArray());
}

Now you can call the method like this:现在您可以像这样调用该方法:

String[] numbers = new String[]{"one", "two", "three"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
System.out.println(Arrays.toString(numbers));

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”数组中的更好方法。

I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size.我在 Java 方面经验不多,但我一直被告知数组是具有预定义大小的静态结构。 You have to use an ArrayList or a Vector or any other dynamic structure.您必须使用 ArrayList 或 Vector 或任何其他动态结构。

您可以创建一个数组列表,并使用Collection.addAll()将字符串数组转换为您的数组列表

你可以简单地这样做:

System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);

If one really want to resize an array you could do something like this:如果真的想调整数组的大小,您可以执行以下操作:

String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr)); 
// Output is: [a, b, c]

arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";

System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]

Size of array cannot be modified.数组的大小不能修改。 If you have to use an array, you can use:如果必须使用数组,可以使用:

System.arraycopy(src, srcpos, dest, destpos, length); 

It's also possible to pre-allocate large enough memory size.也可以预先分配足够大的内存大小。 Here is a simple stack implementation: the program is supposed to output 3 and 5.这是一个简单的堆栈实现:程序应该输出 3 和 5。

class Stk {
    static public final int STKSIZ = 256;
    public int[] info = new int[STKSIZ];
    public int sp = 0; // stack pointer
    public void push(int value) {
        info[sp++] = value;
    }
}
class App {
    public static void main(String[] args) {
        Stk stk = new Stk();
        stk.push(3);
        stk.push(5);
        System.out.println(stk.info[0]);
        System.out.println(stk.info[1]);
    }
}

It is not compiling because an array has no function named append the better and the correct way to go with is to use ArrayList它没有编译,因为数组没有名为 append 的函数更好,正确的方法是使用 ArrayList

import java.util.ArrayList;

ArrayList where = new ArrayList<String>();

where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1")
where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM