我有以下代码:

String[] where;
where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");

这两个追加没有编译。这是如何正确工作的?


当前回答

数组上没有append()方法。相反,如前所述,List对象可以满足动态插入元素的需要。

List<String> where = new ArrayList<String>();
where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");

或者如果你真的很喜欢使用数组:

String[] where = new String[]{
    ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
    ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
};

但这是一个固定的大小,没有元素可以添加。

其他回答

你可以简单地这样做:

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

还有另一个选项,我在这里没有看到,它不涉及“复杂的”对象或集合。

String[] array1 = new String[]{"one", "two"};
String[] array2 = new String[]{"three"};

// declare a new array with enough space for all elements
String[] combinedArray = new String[array1.length + array2.length];

// copy the separate arrays into the combined array
System.arraycopy(array1, 0, combinedArray, 0, array1.length);
System.arraycopy(array2, 0, combinedArray, array1.length, array2.length);

我在Java方面不是很有经验,但我总是被告知数组是具有预定义大小的静态结构。 你必须使用数组列表或者向量或者其他动态结构。

向字符串数组添加新项。

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

它不是编译,因为数组没有名为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")