2013-02-02 74 views
2

的ArrayList你好,我要填寫我的ArrayList ArrayList的命名爲QuestionIdList_Section
爲此,我必須做出一個名爲QUESTION_ID_Of_SectionId_Temp臨時ArrayList中添加到QuestionIdList_Section設置數值爲ArrayList的

我的代碼後,將明確是如下這樣您就可以瞭解我已經codded:

public static ArrayList<String> QUESTION_ID_Of_SectionId_Temp = new ArrayList<String>(); 
public static ArrayList<ArrayList<String>> QuestionIdList_Section = new ArrayList<ArrayList<String>>(); 

QUESTION_ID_Of_SectionId_Temp.add("Hello"); 
QUESTION_ID_Of_SectionId_Temp.add("Hiii"); 

QuestionIdList_Section.add(0,QUESTION_ID_Of_SectionId_Temp); 

Log.i(TAG, "******Before " + QuestionIdList_Section); 
Log.i(TAG, "******Before "+ QUESTION_ID_Of_SectionId_Temp); 

QUESTION_ID_Of_SectionId_Temp.clear(); 

Log.i(TAG, "******After " + QuestionIdList_Section); 
Log.i(TAG, "******After " + QUESTION_ID_Of_SectionId_Temp); 

執行的代碼後,我得到不同的結果兩個變量。

如下:

******Before [[Hello, Hiiii]] 
******Before [Hello, Hiiii] 
******After [[]] 
******After [] 

可以有一個人請幫助我明白我缺乏在這些地方我。我想清除溫度arraylist,這樣我可以把UESTION_ID_Of_SectionId_Temp不同的值,因此對於第二個索引QuestionIdList_Section我將設置值不同。

在此先感謝。

+0

您是否清除了QuestionIdList_Section? –

+0

使用'QUESTION_ID_Of_SectionId_Temp.remove(item)'而不是'QUESTION_ID_Of_SectionId_Temp.clear();' – Deepzz

+0

只是改變'QuestionIdList_Section.add(0,QUESTION_ID_Of_SectionId_Temp);'到'QuestionIdList_Section。添加(0,新的ArrayList (QUESTION_ID_Of_SectionId_Temp));'和你的代碼將工作,因爲你需要複製ArrayList而不是傳遞引用之前清理它 –

回答

3

QUESTION_ID_Of_SectionId_Temp只是一個參考。

因此,如果您清除它,QuestionIdList_Section中的值也將清晰。

你應該做的是

QUESTION_ID_Of_SectionId_Temp = new ArrayList<String>();

,而不是

QUESTION_ID_Of_SectionId_Temp.clear();

+0

謝謝!你救了我幾個小時。 –

1

您正在清理QUESTION_ID_Of_SectionId_Temp陣列,這意味着它沒有元素。第二個「After」打印將其顯示爲空。

第一個「After」顯示上面仍然包含ArrayListQuestionIdList_Section的內容,該內容現在爲空。

2

QuestionIdList_Section相關聯的ArrayList保持參考與QUESTION_ID_Of_SectionId_Temp相關聯的ArrayList
因此,在清除臨時ArrayList時,它也會反映在QuestionIdList_Section的ArrayList中。

您可能希望創建臨時數組的新實例並把它添加到主數組列表如下:

QUESTION_ID_Of_SectionId_Temp = new ArrayList<String>(); 
QuestionIdList_Section.add(QUESTION_ID_Of_SectionId_Temp); 

這樣做之後,每次添加到QUESTION_ID_Of_SectionId_Temp元素將在thew顯示第二個索引QuestionIdList_Section

+0

不錯的答案。感謝您的解釋。 – Maulik