【问题标题】:Setting the Value for Arraylist of Arraylist设置 Arraylist 的 Arraylist 的值
【发布时间】:2013-02-02 08:19:41
【问题描述】:

您好,我想填写名为 QuestionIdList_Section 的 Arraylist 的 Arraylist
为此,我创建了名为 QUESTION_ID_Of_SectionId_Temp 的临时 Arraylist,添加到 QuestionIdList_Section 后会很清楚

我的代码如下,以便您了解我的编码方式:

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 []

有人可以帮助我了解我在这里缺少的地方。我想清除临时数组列表,以便我可以为UESTION_ID_Of_SectionId_Temp 放置不同的值,因此对于QuestionIdList_Section 的第二个索引,我将设置不同的值。

提前致谢。

【问题讨论】:

  • 您清除 QuestionIdList_Section 了吗?
  • 使用QUESTION_ID_Of_SectionId_Temp.remove(item) 而不是QUESTION_ID_Of_SectionId_Temp.clear();
  • 只需将QuestionIdList_Section.add(0,QUESTION_ID_Of_SectionId_Temp); 更改为QuestionIdList_Section.add(0,new ArrayList&lt;String&gt;(QUESTION_ID_Of_SectionId_Temp));,您的代码就可以工作了,因为您需要在清理之前复制 ArrayList 而不是传递引用
  • 你好,作为一个提示,看看java的命名约定:oracle.com/technetwork/java/codeconv-138413.html

标签: java android arraylist


【解决方案1】:

QUESTION_ID_Of_SectionId_Temp 只是一个参考。

所以如果你清除它,QuestionIdList_Section 中的值也会被清除。

你应该做的是

QUESTION_ID_Of_SectionId_Temp = new ArrayList&lt;String&gt;();

而不是

QUESTION_ID_Of_SectionId_Temp.clear();

【讨论】:

  • 谢谢!您节省了我的几个小时。
【解决方案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 的每个元素都将显示在QuestionIdList_Section 的第二个索引中。

【讨论】:

  • 不错的答案。谢谢你的解释。
【解决方案3】:

您正在清除 QUESTION_ID_Of_SectionId_Temp 数组,这意味着它没有元素。第二个“After”打印显示为空。

第一个“After”显示QuestionIdList_Section的内容,上面还包含ArrayList,现在是空的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多