-1
  • 创建一个新的 List,其中包含交错的 list1 的元素
  • 与list2的元素。例如,如果 list1 成立
  • <"over","river","through","woods"> 和 list2 包含 <"the","and","the">,
  • 那么新列表应该保持
  • <"over","the","river","and","through","the","woods">。交替
  • 清单 1 和清单 2。如果一个列表较长,则新列表将包含所有
  • 最后较长列表中的额外值。例如,如果 list1
  • 持有 <"over","river","through","woods"> 和 list2 持有 <"the","and">
  • 那么新列表应该保持
  • <"over","the","river","and","through","woods">。

我编程很烂,看不到这个作业最后一部分的逻辑。感谢您花时间看这个。//*

private static List<String> mergeLists(List<String> list1, List<String> list2) {
    long max = Math.max(((File) list1).length(),((File) list2).length());
    ArrayList<String> newlist = new ArrayList<String>();
    for (int i = 0; i < max; i++) {
        if (i < list1) {
            newlist.append(list1[i]);
            {
        if (i < list2) {
            newlist.append(list2[i]);
        }
    }


            return newlist; 
        }
    }
}
4

1 回答 1

1

你肯定有正确的想法,你几乎明白了。猜猜你不会那么擅长编程:)。List您可以为此使用 a 的属性,而无需转换为 a File

    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        list1.add("over");
        list1.add("river");
        list1.add("through");
        list1.add("woods");

        List<String> list2 = new ArrayList<>();
        list2.add("the");
        list2.add("and");

        mergeLists(list1, list2);
    }

    private static List<String> mergeLists(List<String> list1, List<String> list2) {

        // Get the max length of both arrays
        int max = Math.max(list1.size(), list2.size());

        // Initialize new list
        List<String> newList = new ArrayList<>();

        // add an element of the first list to the new list (if there are more elements)
        // and then add an element from the second list to the new list (if there are more elements)
        // and repeat...
        for (int i = 0; i < max; i++) {
            if (i < list1.size()) {
                newList.add(list1.get(i));
            }

            if (i < list2.size()) {
                newList.add(list2.get(i));
            }
        }

        System.out.println(newList);
        return newList;
    }
于 2020-04-07T21:45:08.190 回答