Expanded Array Manipulation
Explore practical array manipulation methods using external libraries like Apache Commons in Java. Learn to combine, reverse, and remove elements from arrays, including user-defined object arrays. Understand how these techniques simplify coding and improve array operations for beginners.
The ArrayUtils.addAll() method
When returning the array values, we individually access each index, which is a tremendous internal utility that’s able to iterate over the whole array. This was one of the utilities from an internal library. Consider the possibility of external libraries that are imported on demand and constantly updating. Apache Commons is an external library that helps us manipulate an array and has extensive utility for programmers.
The Array.getLength() method returns the length of the array. Here’s a code example:
import java.util.Arrays;
import java.lang.reflect.Array;
import org.apache.commons.lang3.ArrayUtils;
class Main{
public static void main(String[] args){
int[] numberCollection = {1, 2};
//we can get a particular value through index
System.out.println(Array.get(numberCollection, 1));
//we can get the length of the array
System.out.println(Array.getLength(numberCollection));
int[] cartOne = {1, 2, 3, 4};
System.out.println("The length of the first cart : " + cartOne.length);
int[] cartTwo = {5, 200, 36, 4, 78, 123};
System.out.println("The length of the second cart : " + cartTwo.length);
int[] addingCart = ArrayUtils.addAll(cartOne, cartTwo);
System.out.println("Combining two carts, the length has changed : " + addingCart.length);
//we can also see the final output
System.out.println("Adding the cart looks like this : " + Arrays.toString(addingCart));
}
}We get the following output when we run the code above:
2
2
The length of the first cart : 4
The length of the second cart : 6
Combining two carts, the length has changed : 10
Adding the cart looks like this : [1, 2, 3, 4, 5, 200, 36, 4, 78, 123]
In the code above:
- Line 16: The
ArrayUtils