Spaces:
Running
Running
| Write the method | |
| int doubles(ArrayList<Integer> list1, ArrayList<Integer> list2) | |
| which takes two integer reading lists as parameters. | |
| The method returns the number of elements found in both list 1 and list 2. | |
| Example method call: | |
| public static void main(String[] args){ | |
| ArrayList<Integer> list1 = new ArrayList<>(); | |
| ArrayList<Integer> list2 = new ArrayList<>(); | |
| list1.add(1); | |
| list1.add(2); | |
| list1.add(3); | |
| list2.add(3); | |
| list2.add(4); | |
| list2.add(5); | |
| list2.add(6); | |
| int t = doubles(list1, list2); | |
| System.out.println("Doubles: " + t); | |
| } | |
| Program outputs: | |
| Doubles: 1 | |
| import java.util.Random; | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.stream.Collectors; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| test(new int[]{1,2,3,4,5,6,7,8}, new int[]{5,6,7,8,9,10,11,12}); | |
| test(new int[]{10,20,30,40,50,60,70}, new int[]{25,30,35,40,45,50}); | |
| test(new int[]{1,9,2,8,3,7,4,6}, new int[]{10,11,12,3,14,15,16,7,4,99,1,98,2}); | |
| } | |
| public static void test(int[] l1, int[] l2) { | |
| ArrayList<Integer> list1 = new ArrayList<>(); | |
| for (int a : l1) { | |
| list1.add(a); | |
| } | |
| ArrayList<Integer> list2 = new ArrayList<>(); | |
| for (int a : l2) { | |
| list2.add(a); | |
| } | |
| System.out.println("Testing with lists "); | |
| System.out.println("" + list1); | |
| System.out.println("and"); | |
| System.out.println("" + list2); | |
| System.out.println("Doubles: " + doubles(list1, list2)); | |
| System.out.println(""); | |
| } | |
| //ADD | |
| //ASSUME BOTH list1, list2 do not contain dupe elements | |
| public static int doubles(ArrayList<Integer> list1, ArrayList<Integer> list2) { | |
| int count = 0; | |
| // // check Double dtype of each element | |
| // for (int i = 0; i < list1.size(); i++) { | |
| // if (list1.get(i) instanceof Double) { | |
| // count++; | |
| // } | |
| // } | |
| // for (int i = 0; i < list2.size(); i++) { | |
| // if (list2.get(i) instanceof Double) { | |
| // count++; | |
| // } | |
| // } | |
| for (int i: list1) { | |
| if (list2.contains(i)) { | |
| count++; | |
| } | |
| } | |
| return count; | |
| } | |
| } | |
| Testing with lists | |
| [1, 2, 3, 4, 5, 6, 7, 8] | |
| and | |
| [5, 6, 7, 8, 9, 10, 11, 12] | |
| Doubles: 4 | |
| Testing with lists | |
| [10, 20, 30, 40, 50, 60, 70] | |
| and | |
| [25, 30, 35, 40, 45, 50] | |
| Doubles: 3 | |
| Testing with lists | |
| [1, 9, 2, 8, 3, 7, 4, 6] | |
| and | |
| [10, 11, 12, 3, 14, 15, 16, 7, 4, 99, 1, 98, 2] | |
| Doubles: 5 | |