我有以下代码:

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

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


当前回答

您需要使用收集列表。不能重新定义数组的维数。

其他回答

Apache Commons Lang有

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

它返回一个新数组,但如果你真的因为某种原因使用数组,这可能是最理想的方法。

如果你想把数据存储在这样一个简单的数组中

String[] where = new String[10];

你想要添加一些元素,比如数字StringBuilder,这比连接字符串要有效得多。

StringBuilder phoneNumber = new StringBuilder();
phoneNumber.append("1");
phoneNumber.append("2");
where[0] = phoneNumber.toString();

这是构建字符串并将其存储到'where'数组中更好的方法。

您需要使用收集列表。不能重新定义数组的维数。

向字符串数组添加新项。

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

数组大小不可修改。如果你必须使用数组,你可以使用:

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