Given two lists of numbers(called listA and listB),I need to write a Java method which returns a boolean value to state whether or not all the elements in listA are contained in listB.
I can't quite get my code to work as it always seems to be returning false.
public static boolean containsAll( int[] listA, int[] listB) { boolean containsAll = true; int ctr1 = 0, ctr2 = 0; while(ctr1 < listA.length && containsAll) { ctr2 = 0; while(ctr2<listB.length && containsAll) { if(listA[ctr1] != listB[ctr2]) containsAll = false; ctr2++; } ctr1++; } return containsAll; } public static void testContainsAll() { Scanner input1 = new Scanner(System.in); System.out.println("Enter size of first array"); int array1[] = new int[input1.nextInt()]; System.out.println("Enter number of ints required"); for(int i=0; i<array1.length; i++) { array1[i] = input1.nextInt(); } Scanner input2 = new Scanner(System.in); System.out.println("Enter size of second array"); int array2[] = new int[input2.nextInt()]; System.out.println("Enter number of ints required"); for(int i=0; i<array2.length; i++) { array2[i] = input2.nextInt(); } boolean containsAll = containsAll(array1,array2); if(containsAll == true) System.out.print("listB contains all elements of listA"); else System.out.print("listB doesn't contain all elements of listA"); }
new HashSet<>(Arrays.asList(array)).retainAll(otherSet);