Combine Two Lists

less than 1 minute read

The code has been modified slightly and now uploaded to the site.

Question

Question

<— Return Home

Main.java

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        Scanner input = new Scanner(System.in);
        System.out.print("Enter five integers for list1: ");
        for (int i = 0; i < 5; i++){
            list1.add(input.nextInt());
        }
        System.out.print("Enter five integers for list2: ");
        for (int i = 0; i < 5; i++){
            list2.add(input.nextInt());
        }
        ArrayList<Integer> combine = union(list1, list2);
        System.out.println("The combined list is " + combine);
    }

    public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2){
        ArrayList<Integer> theUnion = new ArrayList<Integer>();
        // for (int i = 0; i < (list1.size() + list2.size()); i++){
        //     if (i < list1.size()){
        //         theUnion.add(list1.get(i));
        //     }
        //     else {
        //         theUnion.add(list2.get(i));
        //     }
        // }
        for (int i = 0; i < list1.size(); i++){
            theUnion.add(list1.get(i));
        }
        for (int i = 0; i < list2.size(); i++){
            theUnion.add(list2.get(i));
        }
        return theUnion;
    }
}

<— Return Home

input.txt

3
5
45
4
3
33
51
5
4
13

<— Return Home