Posts

Showing posts from November, 2014

How to remove element from Array in Java with Example

For this example you will need to download  commons-lang-2.6.jar  and set it in your classpath. import java.util.Arrays; import org.apache.commons.lang.ArrayUtils; /** * * Java program to show how to remove element from Array in Java * This program shows How to use Apache Commons ArrayUtils to delete * elements from primitive array. * * @author http://javareinvented.blogspot.in */ public class RemoveObjectFromArray{ public static void main(String args[]) { //let's create an array for demonstration purpose int[] test = new int[] { 101, 102, 103, 104, 105}; System.out.println("Original Array : size : " + test.length ); System.out.println("Contents : " + Arrays.toString(test)); //let's remove or delete an element from Array using Apache Commons ArrayUtils test = ArrayUtils.remove(test, 2); //removing element at index 2 //Size of array must be 1 less than original arr

How to remove items from Collections while iterating through it?

I was trying to remove items from Java Collection using for loop but when the line items.remove() executes, it gives me the exception Exception in thread "main" java.util.ConcurrentModificationException My Code was as follows, List<String> items = new ArrayList<String>(); items.add("1"); items.add("2"); items.add("3"); items.add("4"); for(int i=0; i<items.size(); i++) { String item = (String)items.get(i); if(i==3) items.remove(i); } System.out.println(items); To solve this issue I got an solution as follows, An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method. The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration.