29 March 2010

Adding an element to an array

Valid since: op4j 1.0

Description
Add a new element at the end of an array. This will mean resizing the array.

Scenario
Our ingredients variable, of type String[], contains:
// ingredients == ARRAY [ "Lettuce", "Tomato", "Onion" ]
...and we would like to add a new ingredient, Olive Oil, so that we get:
// ingredients == ARRAY [ "Lettuce", "Tomato", "Onion", "Olive Oil" ]

Recipe
Just use the add(...) action on the array:

ingredients = Op.on(ingredients).add("Olive Oil").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:
ingredients = 
    Op.on(ingredients).addAll("Olive Oil", "Balsamic Vinegar").get();

And finally, let's look at the non-op4j Java equivalent code:
ingredients = Arrays.copyOf(ingredients, ingredients.length + 1);
ingredients[ingredients.length - 1] = "Olive Oil";

No comments:

Post a Comment