List element get and set
In this chapter you will learn:
- How to use methods from List to get and set element
- How to replace an element in a List with set method
Get/set element
List
is used to store elements. Getting
elements out of a List
and
changing the element in a List are two basic operations.
They can be done through the following two methods.
E get(int index)
Returns the element at the specified position in this list.E set(int index, E element)
Replaces the element at the specified position in this list with the specified element (optional operation).
import java.util.ArrayList;
import java.util.List;
/* j a va 2s.c o m*/
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("java2s.com");
System.out.println(list);
System.out.println(list.get(3));
}
}
The output:
Replace an element in a List
The following code replaces the third element in a list.
import java.util.ArrayList;
import java.util.List;
// j a va 2s.c o m
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("java2s.com");
System.out.println(list);
list.set(2, "java 2s .com");
System.out.println(list);
}
}
The output:
From the output we can see that the third element is changed from "3" to "java 2s .com".
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections