The Artima Developer Community
Sponsored Link

Java Buzz Forum
2 ways to Remove Elements/Objects From ArrayList in Java

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Javin Paul

Posts: 1090
Nickname: javinpaul
Registered: Jan, 2012

Javin Paul is Java Programmer working on Finance domain.
2 ways to Remove Elements/Objects From ArrayList in Java Posted: Mar 18, 2014 9:00 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Javin Paul.
Original Post: 2 ways to Remove Elements/Objects From ArrayList in Java
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.
Latest Java Buzz Posts
Latest Java Buzz Posts by Javin Paul
Latest Posts From Java67

Advertisement
There are two ways to remove objects from ArrayList in Java, first, by using remove() method, and second by using Iterator. ArrayList provides overloaded remove() method, one accept index of object to be removed i.e. remove(int index), and other accept object to be removed, i.e. remove(Object obj). Rule of thumb is, If you know index of object, then use first method, otherwise use second method. By the way, you must remember to use ArrayList remove methods, only when you are not iterating over ArrayList, if you are iterating then use Iterator.remove() method, failing to do so may result in ConcurrentModificationException in Java. Another gotcha can be occurred due to autoboxing. If you look closely that two remove methods, remove(int index) and remove(Object obj) are indistinguishable if you are trying to remove from an ArrayList of Integers. Suppose you have three objects in ArrayList i.e. [1,2,3] and you want to remove second object, which is 2. You may call remove(2), which is actually a call to remove(Object) if consider autoboxing, but will be interpreted as a call to remove 3rd element, by interpreting as remove(index). I have discussed this problem earlier on my article about best practices to follow while overloading methods in Java. Because of lesser known widening rule and autoboxing, poorly overloaded method can create lot of ambiguity.
Read more »

Read: 2 ways to Remove Elements/Objects From ArrayList in Java

Topic: Spring Data Couchbase 1.0 GA Released Previous Topic   Next Topic Topic: Atom, Hackable Text Editor By GitHub

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use