我有以下代码:

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

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


当前回答

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

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

其他回答

如果你真的想要调整数组的大小,你可以这样做:

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]

也可以预先分配足够大的内存大小。下面是一个简单的堆栈实现:程序应该输出3和5。

class Stk {
    static public final int STKSIZ = 256;
    public int[] info = new int[STKSIZ];
    public int sp = 0; // stack pointer
    public void push(int value) {
        info[sp++] = value;
    }
}
class App {
    public static void main(String[] args) {
        Stk stk = new Stk();
        stk.push(3);
        stk.push(5);
        System.out.println(stk.info[0]);
        System.out.println(stk.info[1]);
    }
}

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

String[] where = new String[10];

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

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

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