javaarrayslistappendinterleave

How to interleave two arrays into a new array


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

Solution

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