ARRAYLIST
ARRAYLIST
names.add("Lyne");
• Importance: Java requires all code to be inside a class for execution. names.add("Precious");
public static void main(String[] args) { • Importance: Stores the initial names in a dynamic list for further
operations.
• Defines the main() method, the entry point of the Java program.
System.out.println("Changing an Element:");
System.out.println("Adding Elements:");
• Prints "Changing an Element:" to the console.
• Prints "Adding Elements:" to the console.
• Importance: Notifies the user about the modification operation.
• Importance: Demonstrates how to remove an element from an
ArrayList.
names.set(1, "Lendrix");
• Removes the first element ("Jenny") from the list. • Importance: Avoids repetitive code by centralizing list printing in
one method.
list.forEach(name -> System.out.print(name + " ")); • Why it’s used: We need a list to store and manipulate names
efficiently.
• Uses Java’s forEach method with a lambda expression to print all
names in one line. 2. Scanner is for User Input (Not Needed Here)
• Importance: Provides a concise and modern way to iterate over the • Scanner is used when you need to read user input from the
list. keyboard.
• Example:
• Prints a newline (\n) to separate list output sections. System.out.print("Enter a name: ");
This Java program demonstrates four key ArrayList operations: • Why it’s NOT used: Your program doesn’t ask users for input; names
are hardcoded into the ArrayList.
1. Adding elements (add())
3. ArrayList is More Flexible than Scanner
2. Modifying an element (set())
Dynamic Resizing: ArrayList can grow or shrink as needed, unlike arrays.
3. Removing an element (remove())
Easy Element Modification: You can replace, remove, and reorder
4. Displaying the list (using forEach inside printList()) elements easily.
Why is this important? Efficient for Storing and Processing Data: It is not tied to user input like
Scanner.
• ArrayList is a dynamic alternative to arrays in Java.
ArrayList and Scanner serve different purposes in Java. Here’s why ArrayList
is used in your code instead of Scanner: Conclusion
1. ArrayList is for Storing and Managing Data We use ArrayList here because the program is focused on managing a list of
names, not reading user input. If the program required users to type names,
• ArrayList<String> names = new ArrayList<>(); we would use both Scanner (for input) and ArrayList (for storage).
• Purpose: Stores multiple names dynamically and allows easy
modifications (add, remove, update).