Java Arrays Java
It can be accomplished by using Arrays.copyOfRange() as shown in this example:  package com.logicbig.example;
import java.util.Arrays;
public class ArrayRemoveAllBefore { public static void main(String[] args) { String[] anArray = {"one", "two", "three", "four", "five"}; System.out.println("-- original array --"); System.out.println(Arrays.toString(anArray));
System.out.println("-- removing before 'three' inclusively --"); String[] newArray = removeBefore(anArray, "three", true); System.out.println(Arrays.toString(newArray));
System.out.println("-- removing before 'three' not inclusively --"); String[] newArray2 = removeBefore(anArray, "three", false); System.out.println(Arrays.toString(newArray2));
System.out.println("-- removing before 'five' (last element) inclusively --"); String[] newArray3 = removeBefore(anArray, "five", true); System.out.println(Arrays.toString(newArray3));
System.out.println("-- removing before 'five' (last element) not inclusively --"); String[] newArray4 = removeBefore(anArray, "five", false); System.out.println(Arrays.toString(newArray4));
System.out.println("-- removing before 'one' (first element) inclusively --"); String[] newArray5 = removeBefore(anArray, "one", true); System.out.println(Arrays.toString(newArray5));
System.out.println("-- removing before 'one' (first element) not inclusively --"); String[] newArray6 = removeBefore(anArray, "one", false); System.out.println(Arrays.toString(newArray6));
}
public static <T> T[] removeBefore(T[] array, T target, boolean inclusive) { for (int i = 0; i < array.length; i++) { if (array[i].equals(target)) { if (inclusive) { return Arrays.copyOfRange(array, i + 1, array.length); } else { return Arrays.copyOfRange(array, i, array.length);
} } } return array.clone(); } }
Output-- original array -- [one, two, three, four, five] -- removing before 'three' inclusively -- [four, five] -- removing before 'three' not inclusively -- [three, four, five] -- removing before 'five' (last element) inclusively -- [] -- removing before 'five' (last element) not inclusively -- [five] -- removing before 'one' (first element) inclusively -- [two, three, four, five] -- removing before 'one' (first element) not inclusively -- [one, two, three, four, five]
|
|