0

To remove element from ArrayList, we can use-

  1. Iterator remove() is used while iteration.
  2. For ArrrayList remove() no iteration required.

Syntax is different in those cases. So

  • Do both use same logic internally?
  • Is there any more difference than logic?
  • Which one is better?

Any detailed explanation/link is highly appreciated.

3
  • 3
    4. ArrayList.delete() doesn't exist... Commented Jul 30, 2014 at 12:02
  • Oops I typed wrongly. Plz check. edited Commented Jul 30, 2014 at 12:04
  • For future reference : geeksforgeeks.org/remove-element-arraylist-java Commented Nov 29, 2018 at 10:11

2 Answers 2

2

An iterator might throw ConcurrentModificationException if an element is removed from the underlying collection in another way than the iterator's own remove() method.

So if you need to remove elements while iterating over a collection, you're allowed to do that with Iterator.remove() but you can't do that with Collection.remove() without risking to get an exception.

Sign up to request clarification or add additional context in comments.

Comments

0

remove is a method that should be implemented (if no, it should throw UnsupportedOperationException) by all objects that are Iterable (implement interface Itarable). The way it works depends always on the object that implements it.

That means an ArrayList can implement it in a totally different way then i.e. LinkedList.

Removing object in Iterator requires You to iterate (find) the object You want to remove.

Using a remove method in ArrayList (there is no delete I can see in Javadoc: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html) finds the object for You and deletes it. It actually shifts objects in an underlying arrays to fill the "gap" You created by removing the object, so if You want to remove items in a list often, You could use LinkedList Instead.

Additionally while You are iterating through a list, You will cause an exception if You want to modify the collection in some other way than via iterator methods.

The exact answers to Your questions are: 1.No they use diferent logic, and additionally Iterator might even not allow to delete object (UnsupportedOperationException) 2.You cannot remove object by ArrayList remove while You are itereating, and to remove object at position 4 in ArrayList by using Iterator You would have to iterate 4 times "manually". 3.It depends whether You allready know what object do You want to remove, or first You check all the objects and decide whether to delete, during the iteration process. Additionally - If You want to delete objects often, You better use LinkedList, instead of ArrayList.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.