【问题标题】:How can I combine any list? - JAVA如何组合任何列表? - 爪哇
【发布时间】:2017-01-13 04:30:36
【问题描述】:

我有三门课。 Hero 和 Monster 类扩展了 Character 类。 Character 类扩展了 Object 类。

我有 2 个 ArrayList,一个用于英雄,另一个用于怪物。如何在一种方法中将它们组合到一个 arrayList 中。

ArrayList<Hero> heroes = new ArrayList<Hero>();
ArrayList<Monster> monsters = new ArrayList<Monster>();

ArrayList<Character> allCharacters = sumArrays(heroes, monsters);

【问题讨论】:

    标签: java generics arraylist


    【解决方案1】:
    /**
     * doesn't touch the given lists, creates one new list with all the elements inside the given lists.
     * @param lists lists to add together
     * @param <T> A common class between lists
     */
    public static <T> ArrayList<T> sumArrays (ArrayList<? extends T>... lists) {
        ArrayList<T> summed = new ArrayList<T>();
        for (ArrayList<? extends T> list: lists)
            summed.addAll(list);
        return summed;
    }
    

    【讨论】:

      【解决方案2】:

      使用 Java 8:

      public static <T> List<T> sumArrays(List<? extends T>... lists) {
           return Arrays.stream(lists).flatMap(List::stream).collect(Collectors.toList());
      }
      

      还要注意抽象类型List,它优先于具体实现ArrayList - 请参阅Liskov substitution principle。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-25
        • 1970-01-01
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多