Java67 - Java Program Example Tutorial Blog

Java67 - Java Program Example Tutorial Blog


How to remove element from Array in Java with Example

Posted: 25 Dec 2012 05:20 AM PST

There is no direct way to remove elements from Array in Java. Though Array in Java are objects, it doesn't provide any methods to add(), remove() or search an element in Array. This is the reason Collection classes like ArrayList and HashSet are very popular. Thanks to Apache Commons Utils, You can use there ArrayUtils class to remove an element from array more easily than by doing it yourself. One thing to remember is that Arrays are fixed size in Java, once you create an array you can not change there size, which means removing or deleting an item doesn't reduce size of array. This is in-fact main difference between Array and ArrayList in Java. What you need to do is create a new array and copy remaining content of this array into new  array using System.arrayCopy() or any other means. For Object arrays, You can also convert Array to List and then remove a particular object and convert List back to array. One way to avoid this hassle is using ArrayList instead of Array in first place.
Read more »


Post a Comment