I want to copy only "b", "d" and "e" from arr1 to arr2 and increase the size of arr2 dynamically while adding.
I tried adding a if condition
if(!arr1[i].equals("a") && !arr1[i].equals("c")) {
arr2 = Arrays.copyOf(arr1, i + incrementLength);
}
but it still copies everything from arr1 to arr2.
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String[] arr1 = new String[] { "a", "b", "c", "d", "e" };
String[] arr2 = new String[0];
int incrementLength = 1;
for (int i = 0; i < arr1.length; i++) {
if(!arr1[i].equals("a") && !arr1[i].equals("c")) {
arr2 = Arrays.copyOf(arr1, i + incrementLength);
}
}
for (String value : arr2) {
System.out.println(value);
}
}
}
ArrayList? Do you mind usingStreams?Stream,filter,toArraythen ;-)Arrays.copyOf()to truncate the array to fit the elements in there.