ArrayList is present in java.util package and it is the implementation class of List interface. It does allow the duplicates elements and also it maintains the insertion order of the elements. It dynamically resized its capacity. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.
Example: In this program, we will first create an ArrayList of Integers and add elements using add() method, Now we will iterate over the ArrayList elements using the for each loop.
Java
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> gfg = new ArrayList<>();
gfg.add( 1 );
gfg.add( 20 );
gfg.add( 21 );
gfg.add( 13 );
gfg.add( 21 );
gfg.add( 10 );
gfg.add( 21 );
for (Integer value : gfg) {
System.out.println(value);
}
}
}
|
Output
1
20
21
13
21
10
21
Approach(Using replaceAll() method)
In this program, we will create an ArrayList of Integers and add elements in it using add() method, then we will replace all occurrences of 21 with 200 using replaceAll() method.
Syntax:
public static boolean replaceAll(List list, T oldVal, T newVal)
Parameters: This method takes the following argument as a Parameter
- list: the list in which replacement is to occur.
- oldVal: the old value to be replaced.
- newVal: the new value with which oldVal is to be replaced.
Return Value: This method returns true if list contained one or more elements e such that (oldVal==null ? e==null : oldVal.equals(e)).
Example 1:
Java
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> gfg = new ArrayList<>();
gfg.add( 1 );
gfg.add( 20 );
gfg.add( 21 );
gfg.add( 13 );
gfg.add( 21 );
gfg.add( 10 );
gfg.add( 21 );
Collections.replaceAll(gfg, 21 , 200 );
for (Integer value : gfg) {
System.out.println(value);
}
}
}
|
Output
1
20
200
13
200
10
200
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] argv) throws Exception
{
List<String> list = new ArrayList<String>();
list.add( "?" );
list.add( "For" );
list.add( "?" );
System.out.println( "Initial values are :" + list);
Collections.replaceAll(list, "?" , "Geeks" );
System.out.println( "Value after replace :" + list);
}
}
|
Output
Initial values are :[?, For, ?]
Value after replace :[Geeks, For, Geeks]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
15 Nov, 2021
Like Article
Save Article