0

I have a java code where i have an ArrayList and want to remove element from the arraylist.

   ArrayList <word> wordlist=new ArrayList<>();

   public void removeWord(String inputWord){    
        for(word z:wordlist){               
            if(z.getWord() == inputWord)
                wordlist.remove(inputWord);
            System.out.println("the word" +inputWord+ "is removed");
        }
        System.out.println(wordlist.size());
    }

the problem is that the element is not getting removed from the list.

Grisha Weintraub
  • 7,803
  • 1
  • 25
  • 45
coolmego
  • 157
  • 1
  • 3
  • 14

4 Answers4

5

You cannot remove the elements from the list you are iterating upon, using enhanced for-loop. This will apparently work sometimes, but not always, and will throw ConcurrentModificationException.

If you want to remove the elements while you iterate, you would have to use Iterator, which has method Iterator#remove which you can use to remove the current element.

See this tutorial: - http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html to understand how to use iterators.

Also, as others have already mentioned, you should use Object#equals method to compare the contents of your strings. Using == you don't compare the contents, rather you are comparing the reference.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Also see [`ListIterator`](http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html) for even more options for altering the list during iteration. (See [`List.listIterator()`](http://docs.oracle.com/javase/7/docs/api/java/util/List.html#listIterator%28%29)). – Duncan Jones Oct 27 '12 at 08:33
  • Thank you,as i am new to java i don't know much about Iterator, that means that i have to implement Iterator and use the remove method. But how do i use the remove method,i mean what should be condition in the method? – coolmego Oct 27 '12 at 08:33
  • @coolmego. See the tutorial link I have given. It explains how to use iterators. – Rohit Jain Oct 27 '12 at 08:34
  • @coolmego. You can use [`Iterator#next`](http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#next%28%29) method to get the next element. Also, as Duncan mentioned, you can better use `ListIterator`. It has method [`ListIterator#next`](http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#next%28%29) which gives you the next element in the list it is iterating upon. – Rohit Jain Oct 27 '12 at 08:35
  • @coolmego. Also see [`this`](http://stackoverflow.com/questions/6126763/using-two-iterators-in-one-arraylist), [`this`](http://stackoverflow.com/questions/8174964/java-using-iterator-to-search-an-arraylist-and-delete-matching-objects) and [`this`](http://stackoverflow.com/questions/8892027/remove-entries-from-the-list-using-iterator) post for some examples. – Rohit Jain Oct 27 '12 at 08:41
  • @coolmego. Remember to accept this as an answer. by clicking the arrow besides it. – Rohit Jain Oct 27 '12 at 09:04
1

Use z.getWord().equals(inputWord) to compare Strings, and read Rohit's answer!

jlordo
  • 37,490
  • 6
  • 58
  • 83
0

In this case you need to add a "break" statement.

public void removeWord(String inputWord)
{
    for (Word z : wordlist) {
        if (z.getWord().equals(inputWord)) {
            wordlist.remove(z);
            System.out.println("the word" + inputWord + "is removed");
            break;
        }
    }
    System.out.println(wordlist.size());

}

You need to remove word obj from list since list is created for word object. Also use braces for if else statement, that is best code practice.

vels4j
  • 11,208
  • 5
  • 38
  • 63
0

Reason?

Iterators returned by ArrayList is fail-fast in nature.

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Where does this iterator Come from while I am not using it?

For enhanced for loop for collections Iterator gets used so you can not call remove method while you are iterating.

So your loop is same as below

for (Iterator<word> i = c.iterator(); i.hasNext(); ){   

What is the Solution Then ?

You can call iterator.remove(); and change loop based on iterator explicitly rather than implicitly.

    String inputWord = "john";
    ArrayList<String> wordlist = new ArrayList<String>();
    wordlist.add("rambo");
    wordlist.add("john");
    for (ListIterator<String> iterator = wordlist.listIterator(); iterator
            .hasNext();) {
        String z = iterator.next();
        if (z.equals(inputWord)) {
            iterator.remove();
            System.out.println("the word" + inputWord + "is removed");
        }
    }
    System.out.println(wordlist.size());

Now Where Can I Read more?

  1. The For-Each Loop
  2. ArrayList Java docs
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72