List is an interface, the most widely used data structure in java, implements the Collections interface.
List stores a list of objects, in an inserted order, stores duplicate values.
There are different data structure implementations of List interface, like ArrayList class, LinkedList class, Vector class etc.,
1. Insert/Delete a Object in a List
Methods : add(), remove() etc.,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.ArrayList; import java.util.List; public class ListExampleOne { public static void main(String[] args) { /** ArrayList stores the list in the form of arrays inside.. **/ List<String> studentList = new ArrayList<String>(); /** * Adding a student in Student List... using add() method. */ studentList.add("Tom"); studentList.add("Karthick"); studentList.add("Vanila"); System.out.println("Student List:" + studentList); /** * Removing a student in Student List... using remove() method. */ studentList.remove("Karthick"); System.out.println("Student List:" + studentList); } } |
Result:
1 2 |
Student List:[Tom, Karthick, Vanila] Student List:[Tom, Vanila] |
2. Search/Retrieve an Object from a List
Methods : contains(), indexOf() etc.,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.ArrayList; import java.util.List; public class ListExampleOne { public static void main(String[] args) { /** ArrayList stores the list in the form of arrays inside.. **/ List<String> studentList = new ArrayList<String>(); /** * Adding a student in Student List... using add() method. */ studentList.add("Tom"); studentList.add("Karthick"); studentList.add("Vanila"); System.out.println("Student List:" + studentList); /** * Removing a student in Student List... using remove() method. */ boolean isPresent = studentList.contains("Karthick"); System.out.println("Is Karthick Present: " + isPresent); int itemIndex = studentList.indexOf("Tom"); System.out.println("String Object Karthick Index: " + itemIndex); itemIndex = studentList.indexOf("Vanila"); System.out.println("String Object Vanila Index: " + itemIndex); itemIndex = studentList.indexOf("Newcomer"); System.out.println("Object Not Present in the List - Index: " + itemIndex); } } |
Result:
1 2 3 4 5 |
Student List:[Tom, Karthick, Vanila] Is Karthick Present: true String Object Karthick Index: 0 String Object Vanila Index: 2 Object Not Present in the List - Index: -1 |