Really need help Java thanks Method intersect accepts two so

Really need help (Java), thanks!

Method intersect: accepts two sorted array lists of integers as parameters and returns a new list that contains only the elements that are found in both lists. For example, if lists named list1and list2 initially store: [1, 4, 8, 9, 11, 15, 17, 28, 41, 59] [4, 7, 11, 17, 19, 20, 23, 28, 37, 59, 81] Then the call of intersect(list1, list2) returns the list:[4, 11, 17, 28, 59] ]

Print the list that is returned by this method.

Solution

public class Test {

    public static void main(String... args) throws Exception {

        List<String> list1 = new ArrayList<String>(Arrays.asList[1, 4, 8, 9, 11, 15, 17, 28, 41, 59]);

        List<String> list2 = new ArrayList<String>(Arrays.asList[4, 7, 11, 17, 19, 20, 23, 28, 37, 59, 81]);

        System.out.println(new Test().intersect(list1, list2));

        System.out.println(new Test().union(list1, list2));

    }

    public <T> List<T> union(List<T> list1, List<T> list2) {

        Set<T> set = new HashSet<T>();

        set.addAll(list1);

        set.addAll(list2);

        return new ArrayList<T>(set);

    }

    public <T> List<T> intersect(List<T> list1, List<T> list2) {

        List<T> list = new ArrayList<T>();

        for (T t : list1) {

            if(list2.contains(t)) {

                list.add(t);

            }

        }

        return list;

    }

}

or

public static ArrayList<Integer> intersect(ArrayList<Integer> list1, ArrayList<Integer> list2)

    {

        ArrayList<Integer> res = new ArrayList();

        for (int var : list1) {

            if(list2.contains(var))

                res.add(var);

        }

        return res;

    }

Really need help (Java), thanks! Method intersect: accepts two sorted array lists of integers as parameters and returns a new list that contains only the elemen
Really need help (Java), thanks! Method intersect: accepts two sorted array lists of integers as parameters and returns a new list that contains only the elemen

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site