Reputation: 320
I'm trying to take certain elements from one array if they meet a specific criterion and assign them to another array in order. For example:
int[] array1 = {1,2,3,4,5}
int[] array2 = {}
(In terms of array2's length, I have created a separate for loop that iterates through array1 - if the element in array1 meets the criterion, array2.length++. Then I will initialize array2 one array1 has been fully iterated through.)
Let's say only array1[1],[3],[4] meet the criterion, so I want them to be transferred to array2.
So far I've done this:
for (iterate through array1) {
if (array1[i] meets criterion) {
a[i] = b[i];
}
}
I wanted to do a[i] = b[i], but if the index is, say, 4, b[] doesn't have an index 4. What can I do to make sure that array[1],[3],[4] will be assigned to array2 in order - array[1] = array2[0], array1[3] = array2[1], array1[4] = array2[2]?
Upvotes: 0
Views: 7716
Reputation: 43078
You can do this by setting array2 to be the same size as array1, that way in the best case, everything from array1 will be contained in array2.
int[] array1 = {1,2,3,4,5};
int[] array2 = new int[array1.length];
int j = 0;
for (int value : array1) {
if (approved(value)) {
array2[j++] = value;
}
}
This can be bad if the arrays are large enough and very few elements of array1 actually meet your criterion. In that case, it will be better to have the memory grow as needed to fit the elements. You can use an ArrayList for this:
List<Integer> array2 = new ArrayList<>();
for (int value : array1) {
if (approved(value)) {
array2.add(value);
}
}
Upvotes: 1
Reputation: 403
Use an index variable to use with your new array. Create it with value 0 and increase it whenever you add a value to your array.
For the array size problem, I would use ArrayList. You can just add elements to it as it grows dynamically. This even allows you to add without needing the aforementioned index variable.
List<Integer> list = new ArrayList<>();
for (int value : array1) {
if (value meets criterion) {
list.add(value);
}
}
Upvotes: 2