I've adjusted my code to use ArrayList instead of HashMap.
I've included comments to explain what is happening.
I've tried executing the code in the Java Tutor at
Java Tutor - Visualize Java code execution to learn Java online
It produces an error once it reaches "result.add(elem);"
import java.util.ArrayList;
import java.util.Arrays;
public class Kata {
public static int[] arrayDiff(int[] a, int[] b) {
// Initialize ArrayList to add elements from int[] a
ArrayList<String> result = new ArrayList<String>();
// sort int[] b in order to binarySearch it for any element present in int[] a
Arrays.sort(b);
// If an element is present in a but is NOT present in b then add to result ArrayList
for (int elem : a) {
if (Arrays.binarySearch(b, elem) < 0)
result.add(elem); // error occurs here
}
// Initialize integer array to transfer elements from result ArrayList
int[] arr = new int[result.size()];
int i = 0;
for (int elem : result) {
arr[i++] = elem;
}
return arr;
}
// I don't know how to execute the code in Java
// Is this how you call the function?
}
public static int[] main(int[] args) {
arrayDiff({1, 2}, 2, {1}, 1, *z);
}
I tried executing the code but it produces this message:
Error: no suitable method found for add(int)
method java.util.Collection.add(java.lang.String) is not applicable
(argument mismatch; int cannot be converted to java.lang.String)
method java.util.List.add(java.lang.String) is not applicable
(argument mismatch; int cannot be converted to java.lang.String)
method java.util.AbstractCollection.add(java.lang.String) is not applicable
(argument mismatch; int cannot be converted to java.lang.String)
method java.util.AbstractList.add(java.lang.String) is not applicable
(argument mismatch; int cannot be converted to java.lang.String)
method java.util.ArrayList.add(java.lang.String) is not applicable
(argument mismatch; int cannot be converted to java.lang.String)
--- Update ---
I solved it!
My solution works in CodeWars.
For some reason it wasn't executing in the Java Tutor
Here is the final solution I used:
import java.util.ArrayList;
import java.util.Arrays;
public class Kata {
public static int[] arrayDiff(int[] a, int[] b) {
ArrayList<Integer> result = new ArrayList<>();
Arrays.sort(b);
for (int elem : a) {
if (Arrays.binarySearch(b, elem) < 0)
result.add(elem);
}
int[] arr = new int[result.size()];
int i = 0;
for (int elem : result) {
arr[i++] = elem;
}
return arr;
}
}