简体   繁体   中英

How to interleave two arrays into a new array

  • Creates a new List that holds the elements of list1 interleaved
  • with the elements of list2. For example, if list1 holds
  • <"over","river","through","woods"> and list2 holds <"the","and","the">,
  • then the new list should hold
  • <"over","the","river","and","through","the","woods">. Alternating between
  • list1 and list2. If one list is longer, the new list will contain all of
  • the extra values from the longer list at the end. For example, if list1
  • holds <"over","river","through","woods"> and list2 holds <"the","and">
  • then the new list should hold
  • <"over","the","river","and","through","woods">.

I suck at programing and can't see the logic on the last part of this assignment. Thank you for taking the time to look at this. //*

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; 
        }
    }
}

You definitely had the right idea, you almost got it. Guess you don't suck at programming that much:). You can use properties of a List for this, without casting to 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM