Thursday, December 12, 2019

2 Ways To Take Away Elements/Objects From Arraylist Inward Java

There are two ways to take objects from ArrayList inwards Java, first, past times using remove() method, in addition to mo past times using Iterator. ArrayList provides overloaded remove() method, i convey index of the object to last removed i.e. remove(int index), in addition to other convey object to last removed, i.e. remove(Object obj). Rule of pollex is, If you lot know the index of the object, thence purpose the start method, otherwise purpose the mo method. By the way, you lot must yell back to purpose ArrayList take methods, exclusively when you lot are non iterating over ArrayList if you lot are iterating thence purpose Iterator.remove() method, failing to do thence may effect inwards ConcurrentModificationException in Java. Another gotcha tin hand notice receive got occurred due to autoboxing. If you lot await closely that ii take methods, remove(int index) in addition to remove(Object obj) are indistinguishable if you lot are trying to take from an ArrayList of Integers.


Suppose you lot receive got iii objects inwards ArrayList i.e. [1,2,3] in addition to you lot desire to take the mo object, which is 2. You may telephone phone remove(2), which is genuinely a telephone phone to remove(Object) if visit autoboxing, but volition last interpreted every bit a telephone phone to take tertiary element, past times interpreting every bit remove(index).

I receive got discussed this occupation before inwards my article almost best practices to follow spell overloading methods inwards Java. Because of lesser known widening dominion in addition to autoboxing, poorly overloaded method tin hand notice do a lot of ambiguity.




Code Example To Remove Elements from ArrayList

Let's bear witness to a higher house theory alongside a elementary code instance of ArrayList with Integers. Following plan has an ArrayList of Integers containing 1, 2 in addition to 3 i.e. [1, 2, 3], this corresponds precisely to the index.

package test; import java.util.ArrayList; import java.util.List;  /**  *  * @author http://java67.blogspot.com  */  public class JavaTutorial{      /**      * @param args the ascendance occupation arguments      */      public static void main(String[] args) {          List<Integer> numbers = new ArrayList<Integer>();         numbers.add(1);         numbers.add(2);         numbers.add(3);          System.out.println("ArrayList contains : " + numbers);          // Calling remove(index)         numbers.remove(1); //removing object at index 1 i.e. sec Object, which is 2          //Calling remove(object)         numbers.remove(3);      }  }  Output: ArrayList contains : [1, 2, 3] Exception inwards thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2         at java.util.ArrayList.rangeCheck(ArrayList.java:635)         at java.util.ArrayList.remove(ArrayList.java:474)         at test.Test.main(Test.java:33)  Java Result: 1

You tin hand notice run into that mo telephone phone is likewise treated every bit remove(index). The best means to take ambiguity is to convey out autoboxing in addition to supply an actual object, every bit shown below.

System.out.println("ArrayList Before : " + numbers);  // Calling remove(index) numbers.remove(1); //removing object at index 1 i.e. sec Object, which is 2            //Calling remove(object) numbers.remove(new Integer(3));  System.out.println("ArrayList After : " + numbers);  Output : ArrayList Before : [1, 2, 3] ArrayList After : [1]

This time, it works, but I am afraid of lazy developers similar me, which takes autoboxing granted. Now let's convey a await at removing the object from ArrayList spell Iterating over them. You must last familiar alongside Iterator inwards Java, before proceeding further.



Remove Object From ArrayList using Iterator

two ways to take objects from ArrayList inwards Java 2 Ways to Remove Elements/Objects From ArrayList inwards JavaThis is genuinely a subtle item of Java programming, non obvious for start timers, every bit the compiler volition non complain, fifty-fifty if you lot purpose remove() method from java.util.ArrayList, spell using Iterator. You volition exclusively realize your mistake, when you lot run into ConcurrentModificationException, which itself is misleading in addition to you lot may pass countless hours finding approximately other thread, which is modifying that ArrayList, because of Concurrent word. Let's run into an example.

public static void main(String[] args) {          List<Integer> numbers = new ArrayList<Integer>();         numbers.add(101);         numbers.add(200);         numbers.add(301);         numbers.add(400);          System.out.println("ArrayList Before : " + numbers);          Iterator<Integer> itr = numbers.iterator();          // take all fifty-fifty numbers         while (itr.hasNext()) {             Integer release = itr.next();              if (number % 2 == 0) {                 numbers.remove(number);             }         }          System.out.println("ArrayList After : " + numbers);      }  Output :  ArrayList Before : [101, 200, 301, 400]  Exception inwards thread "main" java.util.ConcurrentModificationException         at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)         at java.util.ArrayList$Itr.next(ArrayList.java:831)         at Testing.main(Testing.java:28)

You tin hand notice ConcurrentModificationException, due to telephone phone to remove() method from ArrayList. This is  easy inwards elementary examples similar this, but inwards existent project, it tin hand notice last genuinely tough. Now, to cook this exception, simply supervene upon telephone phone of numbers.remove() to itr.remove(), this volition take electrical flow object you lot are Iterating, every bit shown below :

System.out.println("ArrayList Before : " + numbers);  Iterator<Integer> itr = numbers.iterator();  // take all fifty-fifty numbers while (itr.hasNext()) {     Integer release = itr.next();         if (number % 2 == 0) {        itr.remove();     }  }  System.out.println("ArrayList After : " + numbers);  Output ArrayList Before : [101, 200, 301, 400] ArrayList After : [101, 301]

That’s all on this postal service almost How to take object from ArrayList inwards Java. We receive got learned ii ways to take an object or chemical component from ArrayList. By the way, You should e'er purpose remove(index) to delete object, if you lot are non iterating, otherwise e'er purpose Iterator's remove() method for removing object from ArrayList. By the means to a higher house tips volition run alongside whatever index based List implementation.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures in addition to Algorithms: Deep Dive Using Java
Algorithms in addition to Data Structures - Part 1 in addition to 2
Data Structures inwards Java ix past times Heinz Kabutz

No comments:

Post a Comment