This post originated from an RSS feed registered with Java Buzz
by Javin Paul.
Original Post: How to remove element from Array in Java with Example
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
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
othermeans. 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.