【发布时间】:2015-07-02 01:43:26
【问题描述】:
我有一个循环,其中在循环结束时将 String[] 添加到 ArrayList(在类中声明而不是方法),并且在循环开头说 String[] 被清除其内容:
String[] a = new String[2];
while(true){
a[0] = "";
a[1] = "";
-----some code----
(that adds to a[0] and a[1])
-----some code----
//lets call our ArrayList list
list.add(a);
}
通常情况下,列表中存储的是一个空的String。我认为这是因为 java 进入下一步太快了,但我不确定,请问有什么帮助吗?
这是我所有的代码:
static ArrayList<String[]> Names = new ArrayList<String[]>();
public static void read(BufferedReader stream){
String[] aux = new String[2];
char it = 2;
try{
while(it != (char) -1){
aux[0] = "";
aux[1] = "";
it = (char) stream.read();
while(Character.isLetter(it)){
aux[0] += it;
it = (char) stream.read();
}
it = (char) stream.read();
while(Character.isDigit(it)){
aux[1] += it;
it = (char) stream.read();
}
Names.add(aux);
stream.read();
}
}catch(IOException e){
System.out.print("IOException(read): ");
System.err.println(e.getMessage());
}
}
【问题讨论】:
-
“我认为这是因为 java 进入下一步太快了” 这听起来非常不太可能,除非您有多个线程访问数组或列表。请提供一个简短但完整的程序来演示该问题。 (如果它“经常”发生,那应该相当容易)。
-
如果可以的话,也许可以发布你所有的代码。一定有其他事情发生。
-
您的代码甚至无法编译。
a[1} = "";
标签: java arrays string loops arraylist