$show=/label

Java ArrayList remove Example: How to remove by index, by Value/Object, for a specific range

SHARE:

Java ArrayList remove: How to remove a value from ArrayList in Java by index, by Value/Object, for a specific range of indexes, Example programs for each remove method, Related Scenarios with Exceptions.


How to remove a value from ArrayList in java with example programs.

In this post, we will learn how to program to remove elements from a ArrayList in java. Removing value can be done in three ways.

1) By index
2) By value or Object
3) For a given specific range

ArrayList api provides various methods to do remove operations.

java-arraylist-remove






Removing value by index:


Syntax: public E remove(int index)

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

Example:


package com.adeepdrive.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListRemoveIndexExample {
 public static void main(String[] args) {

  List fruits = new ArrayList();
  fruits.add("Apple");
  fruits.add("Banana");
  fruits.add("Orange");
  System.out.println("Before deleting: " + fruits);
  System.out.println("Removing index 1 value by using remove(int index) method");

  fruits.remove(1);
  System.out.println("After deleting : " + fruits);
 }
}

Output:


Before deleting: [Apple, Banana, Orange]
Removing index 1 value by using remove(int index) method
After deleting : [Apple, Orange]


First added three fruit names to fruits list, Next, invoked remove with index. Removed index 1 value (List index starts from 0 as Arrays) from list which holds value Banana. We can see the output.

Read article on How to iterate String Array in java.

remove(index) method returns deleted value from list.

String removedValue = fruits.remove(1);
System.out.println("Removed value: "+removedValue);


Output:

Removed value: Banana

If the index is outside range of 0 and size-1 of list then it throws IndexOutOfBoundsException.

Removing by Value or Object:

 

Syntax: public boolean remove(Object o)


  1. Removes the first occurrence of the specified element from this list, if it is present.
  2. If the list does not contain the element, it is unchanged.
  3. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

Example:



package com.java.w3schools.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListRemoveValueExample {
 public static void main(String[] args) {

  List colors = new ArrayList();
  colors.add("White");
  colors.add("Red");
  colors.add("Green");
  colors.add("Yellow");
  colors.add("Green");
  System.out.println("Before deleting: " + colors);
  System.out.println("Removing Red color value by using remove(Object value) method");

  boolean isRemoved = colors.remove("Red");
  System.out.println("Removed Status: " + isRemoved);
  System.out.println("After deleting : " + colors);
 }
}

Output:


Before deleting: [White, Red, Green, Yellow, Green]
Removing Red colour value by using remove(Object value) method
Removed Status: true
After deleting : [White, Green, Yellow, Green]

It loops the array and finds the first match for deletion. Next, shifts the next elements internally using System.arrayCopy method.

Duplicate values Scenario:


If to be removed value is present at multiple indexes, it removes the first occurrence and keep the remaining occurrences in list.
In above program "Green" appears twice, if we remove it then first Green will be deleted and second Green remains in list.


boolean isRemoved = colors.remove("Green");
System.out.println("Removed Status: " + isRemoved);
System.out.println("After deleting : " + colors);

Output:


Removed Status: true
After deleting : [White, Red, Yellow, Green]

If the value does not exist, it returns false and list is unchanged.

  boolean isRemoved = colors.remove("Gray"); 
  System.out.println("Removed Status: " + isRemoved); 
  System.out.println("After deleting : " + colors);

Output:


Removed Status: false
After deleting : [White, Red, Green, Yellow, Green]

Removing for a specific range:

 

Syntax: protected void removeRange(int fromIndex, int toIndex)

  1. Removes from this list all of the elements whose index is between fromIndex(inclusive) and toIndex(exclusive).
  2. Shifts any succeeding elements to the left (reduces their index).
  3. This call shortens the list by (toIndex - fromIndex) elements.
  4. If toIndex==fromIndex, this operation has no effect.

removeRange method is protected:

 

Protected methods are accessible in only within package or sub classes. removeRange is protected so directly through ArrayList object we can not call this method. So, We have extended ArrayList in the following program.

Example:

package com.java.w3schools.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListRemoveRangeExample  extends ArrayList{
 public static void main(String[] args) {

  ArrayListRemoveRangeExample numbers = new ArrayListRemoveRangeExample();
  numbers.add(1); // index 0
  numbers.add(2); // index 1
  numbers.add(3); // index 2
  numbers.add(4); // index 3
  numbers.add(5); // index 4
  numbers.add(6); // index 5
  numbers.add(7); // index 6
  numbers.add(8); // index 7
  numbers.add(9); // index 8
  numbers.add(10); // index 9

  System.out.println("Before deleting: " + numbers);
  System.out.println("Removing range from index 2 to 5 by using removeRange(int fromIndex, int toIndex) method");

  numbers.removeRange(2, 5);
  System.out.println("After deleting : " + numbers);
 }
}

Output:


Before deleting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Removing range from index 2 to 5 by using removeRange(int fromIndex, int toIndex) method
After deleting : [1, 2, 6, 7, 8, 9, 10]

If indexes are out of range then IndexOutOfBoundsException will be thrown.

If you like this post, Please share with your friends and leave your questions in comments section.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,72,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,48,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java ArrayList remove Example: How to remove by index, by Value/Object, for a specific range
Java ArrayList remove Example: How to remove by index, by Value/Object, for a specific range
Java ArrayList remove: How to remove a value from ArrayList in Java by index, by Value/Object, for a specific range of indexes, Example programs for each remove method, Related Scenarios with Exceptions.
https://1.bp.blogspot.com/-SQrtoSJ0JZI/Wigq4ocdliI/AAAAAAAAA_E/DeEarnq21Ls1z9RNuLIlJipsQYloPznfACEwYBhgL/s320/java-arraylist-remove.jpg
https://1.bp.blogspot.com/-SQrtoSJ0JZI/Wigq4ocdliI/AAAAAAAAA_E/DeEarnq21Ls1z9RNuLIlJipsQYloPznfACEwYBhgL/s72-c/java-arraylist-remove.jpg
JavaProgramTo.com
https://www.javaprogramto.com/2017/12/java-arraylist-remove.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2017/12/java-arraylist-remove.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content