let's say I have two array;
Integer[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 200, 5, 6, 5 };
Integer[] array2= { 12, 2 ,3, 2, 200, 5 };
Im trying to make a method that return an array with all the element removed except those who are in also present in array2, so the output of this method should be
{2 ,3, 5, 200, 5, 5 }
I dont want to use another data structure and i have no idea how to code what im trying to do, im not sure how i can determinate the resulting array length
thanks
If I understand your question, you could begin by creating a contains(Integer[], Integer)
method. Iterate the array and return true
if the array contains the value.
private static boolean contains(Integer[] a, Integer v) {
for (Integer t : a) {
if (t.equals(v)) {
return true;
}
}
return false;
}
Then you can leverage that to iterate your arrays twice. Once to perform a count, and the second time to populate a newly created array with the count
number of elements. Something like,
public static Integer[] retainAll(Integer[] a, Integer[] b) {
int count = 0;
for (Integer val : a) {
if (contains(b, val)) {
count++;
}
}
Integer[] out = new Integer[count];
count = 0;
for (Integer val : a) {
if (contains(b, val)) {
out[count++] = val;
}
}
return out;
}
Then to test it,
public static void main(String[] args) {
Integer[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 200, 5, 6, 5 };
Integer[] array2 = { 12, 2, 3, 2, 200, 5 };
System.out.println(Arrays.toString(retainAll(array, array2)));
}
Output is the requested
[2, 3, 5, 200, 5, 5]
Of course, you could also use Arrays.asList(T...)
and retainAll()
like
public static Integer[] retainAll(Integer[] a, Integer[] b) {
List<Integer> al = new ArrayList<>(Arrays.asList(a));
al.retainAll(Arrays.asList(b));
return al.toArray(new Integer[al.size()]);
}