I wanted to create a method which can check if two arrays are the same (without using any imports). Order does not matter and it can contain duplicates and the two arrays need to remain the same! My idea was to copy the first array, then compare the copy array to the second array. And if I find a valid pair, delete that item from the copy array, so it can handle the duplications. But I cannot delete any item because of a type mismatch. My code:
Solution.java
public class Solution {
public static boolean areTheyTheSame(int[] a, int[] b)
{
if (a.length == b.length)
{
//fill the temp array with the elements of a
int temp[] = new int[a.length];
for (int i = 0 ; i < a.length ; i++)
{
temp[i] = a[i];
}
//check if the temp array and the b array are the same
for (int i = 0 ; i < a.length ; i++)
{
for (int j = 0 ; j < a.length ; j++)
{
if (temp[i] == b[j])
{
temp[i] = null; // Type mismatch: cannot convert from null to int
}
else
{
return false;
}
}
}
return true;
}
return false;
}
}
Test.java
public class Test {
public static void main(String[] args) {
int[] a = new int[]{121, 144, 19, 161, 19, 144, 19, 11};
int[] b = new int[]{121, 19, 19, 144, 161, 144, 11, 19};
if (Solution.areTheyTheSame(a, b) == true)
{
System.out.println("Equal");
}
else
{
System.out.println("Not equal");
}
}
}