Saturday 9 January 2016

How to remove element from Array in Java with Example

How to remove element from Array in Java with Example
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.   
http://www.spcjaipur.com/java-training-institute-in-jaipur.aspx
 

0 comments:

Post a Comment