List
List is an interface in the Collection Framework that represents an ordered group of elements, where duplicate values are allowed, and each element has a specific position (index), just like an array.
1. What is a List?
List is an interface in the Collection Framework that represents an ordered group of elements, where duplicate values are allowed, and each element has a specific position (index), just like an array.
2. Why is it used?
List is used whenever the order of elements matters, and duplicates are acceptable — like maintaining a list of items in a shopping cart, where the same item could appear more than once.
3. Real-Life Example
Think of a to-do list written on paper. Items are in a specific order, and you could accidentally write the same task twice — both are perfectly fine for a List.
4. Syntax
javaList<DataType> listName = new ArrayList<>(); // or LinkedList, Vector, etc.
5. Example Program
javaimport java.util.List; import java.util.ArrayList; public class ListDemo { public static void main(String[] args) { List<String> tasks = new ArrayList<>(); tasks.add("Read"); tasks.add("Write"); tasks.add("Read"); // duplicate allowed System.out.println(tasks); } }
Output:
[Read, Write, Read]6. Key Points to Remember
Listmaintains insertion order and allows duplicate elements.Listis an interface — you must use an implementing class likeArrayList,LinkedList, orVectorto actually create one.- Elements in a
Listare accessed using a zero-based index, just like arrays.