我有以下代码:

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

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


当前回答

数组的大小不能被修改。如果你想要一个更大的数组,你必须实例化一个新的数组。

更好的解决方案是使用数组列表,它可以根据需要增长。方法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" );

如果你需要把它转换成一个简单的数组…

String[] simpleArray = new String[ where.size() ];
where.toArray( simpleArray );

但你用数组做的大多数事情,你也可以用这个数组列表做:

// iterate over the array
for( String oneItem : where ) {
    ...
}

// get specific items
where.get( 1 );

其他回答

正如tangens所说,数组的大小是固定的。但是你必须先实例化它,否则它将只是一个空引用。

String[] where = new String[10];

这个数组只能包含10个元素。所以一个值只能附加10次。在代码中,您正在访问一个空引用。这就是为什么它不起作用。为了有一个 动态增长的集合,使用数组列表。

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

String[] where = new String[10];

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

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

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

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

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

向字符串数组添加新项。

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

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