As we have seen the implementations of a List are :
Let us see the ArrayList implementation first.
Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to replace the name Kriti with a new name Paul.
import java.util.ArrayList; import java.util.List; public class MyApplication { public static void main(String[] args) { Listx = new ArrayList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); x.set(1,"Paul"); for (String data : x) { System.out.println(data); } } }
So, in the above code we have created an ArrayList x.
Listx = new ArrayList<>();
Now, let us see, how the values are positioned in the List
Now, if we see the above diagram, Kriti resides at position/index 1. So, what we do is, just replace the position/index 1 (i.e. x.set(1,"Paul")) with the new name Paul, using the set() method.
x.set(1,"Paul");
And we get the below output,
Next, let us see the implementation using LinkedList. It is exactly similar to ArrayList.
Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to replace the name Kriti with a new name Paul.
import java.util.LinkedList; import java.util.List; public class MyApplication { public static void main(String[] args) { Listx = new LinkedList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); x.set(1,"Paul"); for (String data : x) { System.out.println(data); } } }