【问题标题】:Adding to list of arraylist添加到arraylist列表
【发布时间】:2020-04-15 15:52:37
【问题描述】:

我正在尝试添加以下两个存储在 tempEdges 中的内容:

  1. [RoyalElephant,IS-A,大象]
  2. [皇家大象,IS-NOT-A,灰色]

虽然我只希望将每个数组列表的最后 2 个元素添加到复制路径中的 2 个数组列表中。

数组列表是:

            public static List<ArrayList<String>> copiedPaths = new ArrayList<>();
            public static List<ArrayList<String>> tempEdges = new ArrayList<>();

功能失调的代码是:

            copiedPaths.get(0).add(tempEdges.get(0).get(1));
            copiedPaths.get(0).add(tempEdges.get(0).get(2));
            copiedPaths.get(1).add(tempEdges.get(1).get(1));
            copiedPaths.get(1).add(tempEdges.get(1).get(2));

这没有按预期工作,因为两个数组都添加了 IS-NOT-A,灰色而不是一个具有 IS-A,大​​象和另一个具有IS-NOT-A,灰色

【问题讨论】:

  • 我知道,这不是问题

标签: java list arraylist nested add


【解决方案1】:
    ArrayList<ArrayList<String>> copiedPaths = new ArrayList<>();
    ArrayList<ArrayList<String>> tempEdges = new ArrayList<>();


    tempEdges.add(new ArrayList<>(Arrays.asList("RoyalElephant", "IS-A", "Elephant")));
    tempEdges.add(new ArrayList<>(Arrays.asList("RoyalElephant", "IS-NOT-A", "Gray")));

    copiedPaths.add(new ArrayList<>(Arrays.asList(tempEdges.get(0).get(1),tempEdges.get(0).get(2))));
    copiedPaths.add(new ArrayList<>(Arrays.asList(tempEdges.get(1).get(1),tempEdges.get(1).get(2))));


    System.out.println(Arrays.toString(copiedPaths.get(0).toArray()));
    System.out.println(Arrays.toString(copiedPaths.get(1).toArray()));

输出:-

[IS-A,大象]

[IS-NOT-A,灰色]

【讨论】:

    【解决方案2】:

    Java 9+ 解决方案:

    List<List<String>> tempEdges = List.of(List.of("RoyalElephant", "IS-A", "Elephant"),
                                           List.of("RoyalElephant", "IS-NOT-A", "Gray"));
    
    List<List<String>> copiedPaths = tempEdges.stream()
            .map(list -> list.subList(1, list.size()))
            .collect(Collectors.toList());
    
    System.out.println(tempEdges);
    System.out.println(copiedPaths);
    

    对于 Java 8+,请使用 Arrays.asList 而不是 List.of

    对于 Java 7+,使用:

    List<List<String>> tempEdges = Arrays.asList(Arrays.asList("RoyalElephant", "IS-A", "Elephant"),
                                                 Arrays.asList("RoyalElephant", "IS-NOT-A", "Gray"));
    
    List<List<String>> copiedPaths = new ArrayList<>();
    for (List<String> list : tempEdges)
        copiedPaths.add(list.subList(1, list.size()));
    
    System.out.println(tempEdges);
    System.out.println(copiedPaths);
    

    输出

    [[RoyalElephant, IS-A, Elephant], [RoyalElephant, IS-NOT-A, Gray]]
    [[IS-A, Elephant], [IS-NOT-A, Gray]]
    

    请注意,subList 创建了底层列表的视图。如果原来的tempEdges列表可以更改,则需要创建一个副本,即更改

    list.subList(1, list.size())
    

    new ArrayList<>(list.subList(1, list.size()))
    

    【讨论】:

    • 谢谢,为什么不使用 .get() 和 .add() 对我不起作用?
    • @MrMosby 因为您从未在 copiedPaths 中创建内部列表。
    猜你喜欢
    • 2014-03-18
    • 2015-03-30
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    相关资源
    最近更新 更多