2016-12-07 68 views
0

這段代碼應該遍歷包含列表的一個LinkedList,該列表包含一個最大爲9的數字序列。關鍵是將一個數字更改爲負數,然後將列表更改爲一個編號返回到包含所有排列的LinkedList。例如:對於集合1 2 3,排列變爲8,從[1 2 3]開始,在第一次迭代之後,它應該包含[[1 2 3] ,[-1 2 3]]的列表,第二次迭代應該包含[[1 2 3], [- 1 2 3], [1 -2 3], [-1 -2 -3]]的鏈接列表,依此類推。 鏈接列表的結束長度應爲2^n,這對於最終輸出是正確的,但實際數據是完全錯誤的。添加到鏈接列表更改初始值

問題:輸出僅顯示列表的第一個數字作爲負數,因此對於上面的示例,只有(-1 2 3)打印了8次。這使我困惑,因爲鏈接列表中的第一個List<Integer>是(1 2 3)。這個程序如何改變我列表中的初始對象,爲什麼它會一直添加一個只有第一個整數已更改的列表?謝謝,

//Will make neg for one place in each list in linked list, adding changed 
//list back to linkedlist 
public void makeNeg(Integer place){ 
    Integer target = 0; 
    List<Integer> hold = new ArrayList<Integer>(); 

    //list is a class variable 
    Iterator<List<Integer>> it = list.iterator(); 
    while(it.hasNext()){ 
     hold = it.next(); 
     target = hold.get(place); 
     target *= -1; 
     hold.set(place, target); 
     list.addLast(hold); 
    } 
} 

//Should run program 
public void run(Integer place){ 
    if(!(number > place)){ 
     System.out.print("---Completed Successfully ---\n"); 
    }else{ 
     makeNeg(place); 
     run(place+1); 
    } 
} 

Output for Integer of 3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
+0

你只有一個'hold'列表,並且對這個單列表進行內聯變更,將它的引用反覆添加到'token'列表中。你需要複製你的'hold'列表。 –

+0

什麼是'list',當你立即用'hold = it.next()'語句替換該列表時,爲什麼要將'hold'初始化爲一個新的'ArrayList'?另外,你是否錯誤地認爲'token.addLast(hold)'會添加'hold'的*拷貝*? – Andreas

+0

...我可能會誤以爲token.addLast(hold)會添加一個保留副本。它只會添加地址,不會添加副本 –

回答

0

我找到了一種方法,通過使用一些代碼從這個鏈接(http://javatechniques.com/blog/faster-deep-copies-of-java-objects/)來回答這個問題。我做了一個實現可序列化的對象,並使用在我鏈接的url處找到的這部分代碼。

public static numbers copy(numbers orig) { 
    numbers obj = null; 
    try { 
     // Write the object out to a byte array 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     ObjectOutputStream out = new ObjectOutputStream(bos); 
     out.writeObject(orig); 
     out.flush(); 
     out.close(); 

     // Make an input stream from the byte array and read 
     // a copy of the object back in. 
     ObjectInputStream in = new ObjectInputStream(
      new ByteArrayInputStream(bos.toByteArray())); 
     obj = (numbers)in.readObject(); 
    } 
    catch(IOException e) { 
     e.printStackTrace(); 
    } 
    catch(ClassNotFoundException cnfe) { 
     cnfe.printStackTrace(); 
    } 
    return obj; 
}