This example will use apache commons ArrayUtils.removeElement to show how to remove an element from an array. Specifically, the utility class will remove the first occurrence it finds and then shift the elements to the left.
Apache Commons @Test
public void remove_element_from_array_apache_commons () {
String [] daysOfWeek = { "Sunday" , "Monday" , "Tuesday" , "Wednesday" ,
"Thursday" , "Friday" , "Saturday" };
String [] favoriteDaysOfTheWeek = ArrayUtils . removeElement ( daysOfWeek , "Monday" );
logger . info ( Arrays . toString ( daysOfWeek ));
assertTrue ( favoriteDaysOfTheWeek . length == 6 );
assertThat ( favoriteDaysOfTheWeek , arrayContaining (
"Sunday" , "Tuesday" , "Wednesday" ,
"Thursday" , "Friday" , "Saturday" ));
}
Remove element from array posted by Justin Musgrove on 23 October 2013
Tagged: java and java-arrays
Share on: Facebook Google+
All the code on this page is available on github:
RemoveElementFromArray.java