問:爲什麼以下打印出來:從Java util列表讀取時,爲什麼所有元素都返回最後一個元素? (廣義)
ChildB___Parent of ChildB
ChildB___Parent of ChildB
相反的是什麼,我認爲它應該打印出來:
ChildA___Parent of ChildA
ChildB___Parent of ChildB
短期自住問題的廣義示例:
import java.util.ArrayList;
import java.util.List;
public class StackExchangeQuestion1 {
public static void main(String[] args){
List<String[]> list = new ArrayList();
String[] pair = {"childID","parentID"}; //for readability this gets overwritten
//adding values to list
pair[0] = "ChildA";
pair[1] = "Parent of ChildA";
list.add(pair);
pair[0] = "ChildB";
pair[1] = "Parent of ChildB";
list.add(pair);
//checking values in list
for(int i=0;i<list.size();i++){
pair = list.get(i); //variable reuse for readability
System.out.println(pair[0]+"___"+pair[1]);
}
}}//end class and main
注意:我搜索了以前的答案,這是至少2的副本http://stackoverflow.com/questions/10509335/referencing-a-java-list-always-returns-the-last-element http ://stackoverflow.com/questions/4324754/why-all-elements-of-my-list-seems-to-be-the-same --- 我提出了一個新的問題,因爲那些不是短自包含的通用問題/問題的例子,而且不是讀者友好的。 (代碼做了10件事,但問題只涉及1件事)我也不想用我自己的方式劫持他們的問題。 – neokyle
我試過用循環內容替換:System.out.println(list。得到(ⅰ)[0] + 「___」 + list.get(I)[1]);我也嘗試過使用arraylist,都沒有工作。 – neokyle