java - retain specific elements in an array from an array that are in another array -
let's have 2 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 create method homecoming array element removed except in nowadays in array2, output of method should be
{2 ,3, 5, 200, 5, 5 } i dont want utilize info construction , have no thought how code im trying do, im not sure how can determinate resulting array length
thanks
if understand question, begin creating contains(integer[], integer) method. iterate array , homecoming true if array contains value.
private static boolean contains(integer[] a, integer v) { (integer t : a) { if (t.equals(v)) { homecoming true; } } homecoming false; } then can leverage iterate arrays twice. 1 time perform count, , sec time populate newly created array count number of elements. like,
public static integer[] retainall(integer[] a, integer[] b) { int count = 0; (integer val : a) { if (contains(b, val)) { count++; } } integer[] out = new integer[count]; count = 0; (integer val : a) { if (contains(b, val)) { out[count++] = val; } } homecoming out; } then 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 requested
[2, 3, 5, 200, 5, 5] of course, utilize arrays.aslist(t...) , retainall() like
public static integer[] retainall(integer[] a, integer[] b) { list<integer> al = new arraylist<>(arrays.aslist(a)); al.retainall(arrays.aslist(b)); homecoming al.toarray(new integer[al.size()]); } java arrays retain
No comments:
Post a Comment