merge two arraylist lists in list1 while it remain sorted

后端 未结 7 570
再見小時候
再見小時候 2021-01-16 10:43

In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 remains sorted.

I write my code but it

7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-16 11:23

    If your input Lists aren't too long, I'd suggest just merging the lists and using the Collections.sort() Method to restore the order:

    public static void mergeAndSort(List list1, List list2) {
        List combinedList = new ArrayList(list1);
        combinedList.addAll(list2);
        Collections.sort(combinedList);
        return combinedList;
    }
    

    As a sidenote, you should use the List interface instead of the ArrayList implementation class wherever possible.

提交回复
热议问题