29 March 2010

Adding an element to an array at a specific position

Valid since: op4j 1.0

Description
Insert a new element into an array at a specific position.

Scenario
Our minerals variable, of type String[], contains:
// minerals == ARRAY [ "Talc", "Quartz", "Diamond" ]
...and we want to add "Fluorite" at the second position of the array, as it is harder than talc but softer than quartz:
// minerals == ARRAY [ "Talc", "Fluorite", "Quartz", "Diamond" ]

Recipe
Use the insert(...) action on the array, specifying the position at which the new element will be added to the array. Positions start with zero.

minerals = Op.on(minerals).insert(1 ,"Fluorite").get();

Comments
This recipe is also valid for lists, maps and sets.

If we wanted to add more than one element, we could have done:
minerals = 
    Op.on(minerals).insertAll(1, "Fluorite", "Apatite").get();

Let's see the equivalent non-op4j Java code:
minerals = Arrays.copyOf(minerals, minerals.length + 1);
for (int i = (minerals.length - 1), z = 1; i > z; i--) {
    minerals[i] = minerals[i - 1];
}
minerals[1] = "Fluorite";

No comments:

Post a Comment