-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompareTwoArray.java
56 lines (43 loc) · 1.66 KB
/
CompareTwoArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class CompareTwoArray {
/**
* Main method of the class for the following question:
* Checks if two arrays contain the same elements.
* */
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.print("Enter length of array 1: ");
int length = scanner.nextInt();
Integer[] arr1 = new Integer[length];
System.out.println("Enter elements of array 1: ");
for (int i = 0; i < arr1.length; i++) {
arr1[i] = scanner.nextInt();
}
System.out.print("Enter length of array 2: ");
int length2 = scanner.nextInt();
Integer[] arr2 = new Integer[length2];
System.out.println("Enter elements of array 1: ");
for (int i = 0; i < arr2.length; i++) {
arr2[i] = scanner.nextInt();
}
System.out.println("Array 1: " + Arrays.toString(arr1));
System.out.println("Array 2: " + Arrays.toString(arr2));
System.out.println("Are two arrays same: " + isSameElements(arr1, arr2));
}
private static boolean isSameElements(Object[] arr1, Object[] arr2) {
Set<Object> uniqueElements1 = new HashSet<>(Arrays.asList(arr1));
Set<Object> uniqueElements2 = new HashSet<>(Arrays.asList(arr2));
if (uniqueElements1.size() != uniqueElements2.size()) {
return false;
}
for (Object obj : uniqueElements1) {
if (!uniqueElements2.contains(obj)) {
return false;
}
}
return true;
}
}