2017-08-01 109 views
0

我試圖把integer列表中的整數列表中的整數列表。 我試過了。ArrayList輸出的ArrayList

public class test3{ 
    public static void main(String[] args) throws IOException{ 
     String text= null; 
     ArrayList<ArrayList<Integer>> outerlist = new ArrayList<ArrayList<Integer>>(); 
     ArrayList<Integer> innerlist = new ArrayList<>(); 

     int dept= 17; 
     int arrv= 6; 
     int[] arr = new int[1000]; 
     String[] stations = null;  
     FileReader file = new FileReader("test2.txt"); 
     BufferedReader br = new BufferedReader(file); 
     while((text = br.readLine()) != null){ 
      innerlist.clear(); 
      stations = text.split(" "); 
      //int[] array = Arrays.stream(stations).mapToInt(Integer::parseInt).toArray(); 

      for(int i = 0 ; i<stations.length ; i++){ 
       arr[i] = Integer.parseInt(stations[i]); 
      } 
      for(int j = 0 ; j<stations.length ; j++){ 
       innerlist.add(arr[j]); 
      } 
      outerlist.add(innerlist); 

     } 
     System.out.println(outerlist); 
    } 
} 

它應該輸出 [[1,17,3,150,22],[2,6,34,118],[5,22,3,19,6,118,250,7 ],[10,15,89,14,33,77,2,101,50,44]]

但是相反,它輸出: [[10,15,89,14,33,77,2, [10,15,89,14,33,77,2,101,50,44],[10,15,89,14,33,77,2,101,50,44]中的任何一個, [10,15,89,14,33,77,2,101,50,44]]

測試文件我是從(的test2.txt)讀取包含:

回答

2

只要改變innerlist.clear()innerlist = new ArrayList<>();

當您將內部列表添加到外部列表時,它將按內存地址添加,因此,當您更改內部列表時,它會在所有位置更改。但是當你做innerlist = new ArrayList<>();你創建了新的列表,並且內存加法器被改變了,但它的數據沒有改變