Navigating Java Collections: Lists, Iterators, and HashSets

Traversing ArrayList with Iterator

The following demonstration illustrates how to populate an ArrayList and traverse its contents using the Iterator itnerface. This approach allows for safe removal of elements during iteraiton, though this specific example focuses on retrieval.

package com.demo.collections;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListIteratorDemo {
    public static void main(String[] args) {
        // Initialize a list to store user names
        List<String> userDatabase = new ArrayList<>();
        userDatabase.add("Alice");
        userDatabase.add("Bob");
        userDatabase.add("Charlie");
        userDatabase.add("Diana");

        // Obtain an iterator for the list
        Iterator<String> cursor = userDatabase.iterator();
        
        // Iterate through all available elements
        while (cursor.hasNext()) {
            String currentUser = cursor.next();
            System.out.println("User: " + currentUser);
        }
    }
}

LinkedList Specific Operations

Unlike ArrayList, LinkedList provides specialized methods for manipulating elements at the ends of the list. The example below demonstrates adding and removing elemants from the head of the list.

package com.demo.collections;

import java.util.LinkedList;

public class DequeOperations {
    public static void main(String[] args) {
        LinkedList<String> taskQueue = new LinkedList<>();
        
        // Append tasks to the end
        taskQueue.add("Task A");
        taskQueue.add("Task B");
        taskQueue.add("Task C");
        
        // Insert a high priority task at the beginning
        taskQueue.addFirst("High Priority");
        
        // Insert a specific task at index 3
        taskQueue.add(3, "Mid Priority");
        
        System.out.println("Initial Queue: " + taskQueue);
        System.out.println("Head Element: " + taskQueue.getFirst());
        
        // Remove the head and the element at index 3
        taskQueue.removeFirst();
        taskQueue.remove(3);
        
        System.out.println("Modified Queue: " + taskQueue);
    }
}

Enhanced For-Loop Traversal

For read-only operations, the enhanced for-loop (foreach) provides a cleaner syntax compared to explicit iterators. The following code populates a list and prints each element using this syntax.

package com.demo.collections;

import java.util.ArrayList;

public class EnhancedForLoopDemo {
    public static void main(String[] args) {
        ArrayList<String> inventory = new ArrayList<>();
        inventory.add("Laptop");
        inventory.add("Mouse");
        inventory.add("Keyboard");
        
        // Simplified traversal syntax
        for (String item : inventory) {
            System.out.println("Item: " + item);
        }
    }
}

Storing Custom Objects in HashSet

When storing custom objects in a HashSet, it is critical to override equals() and hashCode() to ensure uniqueness based on logical state rather than memory reference. The following classes define a User object and test duplication logic within a set.

package com.demo.sets;

public class User {
    private String username;
    private int userId;

    public User(String username, int userId) {
        this.username = username;
        this.userId = userId;
    }

    @Override
    public String toString() {
        return "User{name='" + username + "', id=" + userId + "}";
    }

    @Override
    public int hashCode() {
        int result = username != null ? username.hashCode() : 0;
        result = 31 * result + userId;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        User user = (User) obj;
        return userId == user.userId && 
               (username != null ? username.equals(user.username) : user.username == null);
    }
}
package com.demo.sets;

import java.util.HashSet;
import java.util.Set;

public class SetUniquenessTest {
    public static void main(String[] args) {
        Set<User> registeredUsers = new HashSet<>();
        
        // Add distinct users
        registeredUsers.add(new User("alice_dev", 101));
        registeredUsers.add(new User("bob_admin", 102));
        
        // Attempt to add a duplicate logical object
        registeredUsers.add(new User("alice_dev", 101));
        
        // Output will show only two entries due to equals/hashCode contract
        for (User u : registeredUsers) {
            System.out.println(u);
        }
    }
}

Tags: java-collections ArrayList linkedlist HashSet iterator

Posted on Mon, 03 Aug 2026 16:13:56 +0000 by janhouse00