I have written the code for a program that takes two Lists and returns true if all the elements of the second array also occur in the first array. However, this code only works for two arrays that are equal in size (e.g {1, 2, 3} and {3, 2, 1} returns true) but if the first array is larger than the second I get a rangeCheck exception (was fully expecting this, to be fair).
import java.util.*;
public class Ex8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many numbers do you wish to enter into the
array?");
int thisMany = scanner.nextInt();
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Please enter some numbers, separated by
spaces");
for(int i = 0; i<thisMany; i++) {
int x = scanner.nextInt();
numbers.add(x);
}
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers do you wish to enter into the
second array?");
int nowThisMany = sc.nextInt();
ArrayList<Integer> numbers2 = new ArrayList<Integer>();
System.out.println("Enter some numbers, separated by spaces");
for(int j = 0; j<nowThisMany; j++) {
int y = sc.nextInt();
numbers2.add(y);
}
System.out.println(Arrays.toString(numbers.toArray()));
System.out.println(Arrays.toString(numbers2.toArray()));
isContained(numbers, numbers2);
System.out.println(isContained(numbers, numbers2));
}
public static boolean isContained(ArrayList<Integer> numbers,
ArrayList<Integer> numbers2) {
boolean equalsTest = false;
for(int i = 0; i<numbers.size(); i++) { //This gives exception if
//both arrays aren't the same size
if(numbers.get(i) == numbers2.get(i)) {
equalsTest = true;
}
}
return equalsTest;
}
}
Can anyone explain to me how I can check the second array against the first array without running into exception? Thanks