我有以下代码:
String[] where;
where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
这两个追加没有编译。这是如何正确工作的?
我有以下代码:
String[] where;
where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
这两个追加没有编译。这是如何正确工作的?
当前回答
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);
}
其他回答
数组的大小不能被修改。如果你想要一个更大的数组,你必须实例化一个新的数组。
更好的解决方案是使用数组列表,它可以根据需要增长。方法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 );
如果你真的想要调整数组的大小,你可以这样做:
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]
这是我写的代码!它像魔法一样有效!
public String[] AddToStringArray(String[] oldArray, String newString)
{
String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
newArray[oldArray.length] = newString;
return newArray;
}
希望你喜欢!!
如果你想把数据存储在这样一个简单的数组中
String[] where = new String[10];
你想要添加一些元素,比如数字StringBuilder,这比连接字符串要有效得多。
StringBuilder phoneNumber = new StringBuilder();
phoneNumber.append("1");
phoneNumber.append("2");
where[0] = phoneNumber.toString();
这是构建字符串并将其存储到'where'数组中更好的方法。
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);
}