我有以下代码:
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[] where = new String[10];
你想要添加一些元素,比如数字StringBuilder,这比连接字符串要有效得多。
StringBuilder phoneNumber = new StringBuilder();
phoneNumber.append("1");
phoneNumber.append("2");
where[0] = phoneNumber.toString();
这是构建字符串并将其存储到'where'数组中更好的方法。
其他回答
Apache Commons Lang有
T[] t = ArrayUtils.add( initialArray, newitem );
它返回一个新数组,但如果你真的因为某种原因使用数组,这可能是最理想的方法。
我在Java方面不是很有经验,但我总是被告知数组是具有预定义大小的静态结构。 你必须使用数组列表或者向量或者其他动态结构。
它不是编译,因为数组没有名为append的函数更好,正确的方法是使用ArrayList
import java.util.ArrayList;
ArrayList where = new ArrayList<String>();
where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1")
where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1")
也可以预先分配足够大的内存大小。下面是一个简单的堆栈实现:程序应该输出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]);
}
}
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);
}