我有以下代码:

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

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


当前回答

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

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

其他回答

数组上没有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);

Apache Commons Lang有

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

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

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

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

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