95.3k views
11 votes
Write a method intersect that 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.

User Krrishna
by
4.2k points

1 Answer

7 votes

Answer:

Step-by-step explanation:

The following code is written in Java. It creates a function called equalElements that takes two ArrayList of integers as parameters loops through both of them to find the elements that are equal in both and then adds those elements to a new ArrayList called repeated. Then the ArrayList is returned to the user.

public static ArrayList<Integer> equalElements(ArrayList<Integer> arrOne, ArrayList<Integer> arrTwo) {

ArrayList<Integer> repeated = new ArrayList<>();

for (int x: arrOne) {

for (int i: arrTwo) {

if (x == i) {

repeated.add(x);

break;

}

}

}

return repeated;

}

User Santanu Biswas
by
4.9k points