【问题标题】:how to add in arrayList objects like { "color", "red", "style", "blue" }如何添加 arrayList 对象,如 { "color", "red", "style", "blue" }
【发布时间】:2018-10-26 00:00:46
【问题描述】:

嘿,我遇到了一个与 ArrayList 相关的问题,我想在其中添加这样的对象 {“color”、“red”、“style”、“blue”}。

ArrayList<Object[][]> TAGS = new ArrayList<Object[][]>();

for(int i=0;i<5;i++){
    TAGS.add({ "color", "red", "style", "blue" });
}

如果有什么问题,请原谅我,因为我不是经验丰富的程序员。 提前谢谢

【问题讨论】:

  • 试试这个{TAGS.add(new Object[][]{{ "color", "red", "style", "blue" }});} 但我不确定是不是你的意思
  • 为什么需要二维数组结构?
  • 请创建一个包含两个变量(颜色和样式)的类,然后添加该类的实例(对象)。
  • 嘿!你能再帮我一个忙吗?我将如何迭代我的 ArrayList !
  • 是的! “阿米特”你是对的,但这是我想知道这是怎么发生的

标签: java object arraylist


【解决方案1】:

我认为您存储的所有值都是字符串

试试

    List<List<String>> TAGS = new ArrayList<>();

    TAGS.add(Arrays.asList("color", "red", "style", "blue"));
    TAGS.add(Arrays.asList( "tags", "one", "style", "blue"));
    TAGS.add(Arrays.asList( "weapon"));

    System.out.println(TAGS);

【讨论】:

  • 谢谢你!它是有效的,但如果我想列出这样的东西怎么办 [{ “color”, “red”, “style”, “blue” },{ “tags”, “one”, “style”, “blue” },{ “武器" }];
【解决方案2】:

您可能想要创建一个字符串数组的arrayList。 您可以通过

 List<String[]> strings = new ArrayList<>();
 strings.add( new String[] {"Python","Java","Javascript"} );
 strings.add( new String[] {"one","two","three"} );

【讨论】:

  • 嘿,这就是想要的输出 [{"Python","Java","Javascript"},{"one","two","three"},{"Python", "Language"},{"name","class"}] 可以吗?
  • 你的意思是输出将是一个字符串数组列表作为python?
  • 您可以通过 for (String[] s : strings) { for(int i = 0; i
【解决方案3】:

如果您正在寻找嵌套列表,您可以执行以下操作:

        List<List<String>> nestedArrayList = new ArrayList<>();
        List<String> firstList = new ArrayList<String>();
        firstList.add("color");
        firstList.add("red");
        firstList.add("style");
        firstList.add("blue");
        nestedArrayList.add(firstList);

【讨论】:

    猜你喜欢
    • 2022-12-29
    • 1970-01-01
    • 2010-09-26
    • 2021-05-26
    • 2019-02-18
    • 1970-01-01
    相关资源
    最近更新 更多