

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


import java.util.LinkedList; import java.util.Iterator; public class LinkedListExercise { public static void main(String[] args) { // 1. Create a LinkedList object of type String LinkedList wishlist = new LinkedList<>(); // 2. Add elements using various add methods wishlist.add("Laptop"); wishlist.addFirst("Monitor"); // Add to the beginning wishlist.addLast("Mouse"); // Add to the end wishlist.add(1, "Keyboard"); // Add at a specific index (index 1) // 3. Display the initial list and its size System.out.println("Initial Wishlist: " + wishlist); System.out.println("Size of the list: " + wishlist.size()); // 4. Access elements String firstItem = wishlist.getFirst(); // Get the first element String lastItem = wishlist.getLast(); // Get the last element String itemAtIndex2 = wishlist.get(2); // Get element at index 2 System.out.println("\nFirst item: " + firstItem); System.out.println("Last item: " + lastItem); System.out.println("Item at index 2: " + itemAtIndex2); // 5. Modify an element wishlist.set(2, "Gaming Console"); // Replace the element at index 2 System.out.println("\nUpdated Wishlist after set(2, 'Gaming Console'): " + wishlist); // 6. Check if an element exists boolean hasLaptop = wishlist.contains("Laptop"); System.out.println("Does the list contain 'Laptop'? " + hasLaptop); // 7. Remove elements using various remove methods wishlist.removeFirst(); // Remove the first element wishlist.removeLast(); // Remove the last element wishlist.remove("Laptop"); // Remove a specific object System.out.println("\nWishlist after removing first, last, and 'Laptop': " + wishlist); // 8. Iterate through the list using an Iterator System.out.println("\nIterating through the remaining wishlist:"); Iterator iterator = wishlist.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next());
// 9. Clear the entire list wishlist.clear(); System.out.println("\nWishlist after clear(): " + wishlist); System.out.println("Is the list empty? " + wishlist.isEmpty()); } }