如何给java足够的时间为变量赋值?

我有一个循环,在循环结束时将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 Names = new ArrayList(); 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()); } } 

当您将a (或第二个示例中的aux )引用的数组添加到列表中时,变量a仍然引用字符串数组。 当您将字符串数组元素重新初始化为空字符串时,您还会擦除列表中的条目,因为它们是相同的数据结构。 您有多个对同一数组的引用。

您需要为每次循环创建一个新数组,以便列表元素实际上包含单独的数组。 移动初始化数组的行

 String[] a = new String[2]; 

到while循环内部。 这样,数组将被重新分配,以便局部变量不会指向您之前添加到arrayList的同一个数组。

这是一个重现问题的小测试程序:

 import java.util.*; public class DupeArr { public void testBad() { System.out.println("bad, multiple references to same array"); List list = new ArrayList(); String[] arr = {"a", "b"}; for (int i = 0; i < 2; i++) { arr[0] = "" + i; arr[1] = "" + (i * 10); list.add(arr); } System.out.println(list.get(0)[0]); System.out.println(list.get(0)[1]); System.out.println(list.get(1)[0]); System.out.println(list.get(1)[1]); System.out.println(list.get(0)[0].equals(list.get(1)[0])); System.out.println(list.get(0)[1].equals(list.get(1)[1])); // printing true means these lists point to the same array System.out.println("same reference=" + (list.get(0) == list.get(1))); } public void testGood() { System.out.println("good, new array for each list item"); List list = new ArrayList(); for (int i = 0; i < 2; i++) { String[] arr = {"a", "b"}; arr[0] = "" + i; arr[1] = "" + (i * 10); list.add(arr); } System.out.println(list.get(0)[0]); System.out.println(list.get(0)[1]); System.out.println(list.get(1)[0]); System.out.println(list.get(1)[1]); System.out.println(list.get(0)[0].equals(list.get(1)[0])); System.out.println(list.get(0)[1].equals(list.get(1)[1])); // printing false means these lists point to different arrays System.out.println("same reference=" + (list.get(0) == list.get(1))); } public static void main(String[] args) { DupeArr dupeArr = new DupeArr(); dupeArr.testBad(); dupeArr.testGood(); } } 

这个输出是

 bad, multiple references to same array 1 10 1 10 true true same reference=true good, new array for each list item 0 0 1 10 false false same reference=false