2014-11-08 40 views
1

我有一個小的Java應用程序,將執行一些數學函數。無論如何,我有這個代碼創建點並將它們添加到另一個結構中,以便稍後使用這些值。這是代碼鏈接列表非常奇怪的刪除

/*for the sake of the example, this part is fine. these two variables are filled 
earlier but this is how they are initialized */ 
LinkedList<Point> col = new LinkedList<Point>(); 
LinkedList<Point> row = new LinkedList<Point>(); 
/* Issue area below */ 
LinkedList<Point> added = new LinkedList<Point>(); 
while(!col.isEmpty()){ 
    LinkedList<Point> tempRow = row; 
    while(!tempRow.isEmpty()){ 
     added.add(new Point(col.getFirst().x,tempRow.getFirst().y)); 
     tempRow.remove(); 
    } 
    col.remove(); 
} 

當運行此代碼行tempRow.remove()以某種方式從實際行取出爲好。這對我來說沒有意義,因爲我創建了一個局部變量temp並調用了THAT實例變量。有人可以解釋爲什麼會這樣嗎?

+0

謝謝你的提示!現在你能解釋爲什麼刪除臨時變量會從兩者中刪除嗎? – user3704079 2014-11-08 03:21:32

回答

2

我認爲你是錯上以下行

LinkedList<Point> tempRow = row;

這並不是創造一個全新的列表的效果。這僅僅爲您命名爲tempRowrow創建了一個別名。對其中一項的修改也會影響另一項。

你可以做的是創建一個新的LinkedList,然後添加從行到它的所有內容。

LinkedList<Point> tempRow = new LinkedList<Point>(row);

這樣tempRow將是一個新的列表,將包含來自行中的所有的點。

+0

在三分鐘內我很難接受這個。這是我所擔心的。感謝您清理它並提供解決方案! – user3704079 2014-11-08 03:26:37

+0

upvote and accept? =) – Eric 2014-11-08 03:27:10

+0

即時通訊還不夠級別upvote呢!當我有足夠的時間,即時通訊回到upvote它大聲笑 – user3704079 2014-11-08 03:27:36