java - How to create an Array without knowing the length it will have -
this question has answer here:
- java dynamic array sizes? 16 answers
i've got problem solve follows:
create method returns array contains positive values of
int[] a
i've kinda solved writing method:
public static int[] solopositivi(int[] a) { int[] pos = new int[a.length]; int j=0; (int i=0; i<a.length; i++){ if (a[i]>0) { pos[j] = a[i]; j++; } } return pos; }
of course when test using example:
int[] = new int[] {2,-3,0,7,11};
i [2,7,11,0,0]
, because set:
int[] pos = new int[a.length];
the question is, how pos array have modular length can [2,7,11]
, without having use lists? have solve problem using arrays methods.
first, loop through , count number of positive elements know length, loop through again copy.
public static int[] copypositivevals(int[] arr) { int count = 0; for(int x : arr) { if (x > 0) count++; } int[] arr2 = new int[count]; int = 0; for(int x : arr) { if (x > 0) { arr2[i] = x; i++; } } return arr2; }
Comments
Post a Comment