DEV Community

realNameHidden
realNameHidden

Posted on

Scenario based java interview question

Question: You need to store unique user IDs for a web application.

Which collection would be most suitable for this purpose, and why?

Answer: I would use a HashSet for storing unique user IDs because it does not allow duplicate entries and offers average O(1) time complexity for add, remove, and contains operations. Here’s an example:

Addition (add()): O(1) average case, O(n) worst case.
Removal (remove()): O(1) average case, O(n) worst case.
Search (contains()): O(1) average case, O(n) worst case.

package com.example.demo;

import java.util.HashSet;

public class UserManager {

    private HashSet<String> userIDs;

    public UserManager() {
        userIDs = new HashSet<>();
    }

    public boolean addUserID(String userID) {
        return userIDs.add(userID); // returns false if the userID already exists
    }

    public boolean removeUserID(String userID) {
        return userIDs.remove(userID);
    }

    public boolean containsUserID(String userID) {
        return userIDs.contains(userID);
    }

    public static void main(String[] args) {
        UserManager manager = new UserManager();
        manager.addUserID("user123");
        System.out.println(manager.containsUserID("user123")); // Output: true
        manager.removeUserID("user123");
        System.out.println(manager.containsUserID("user123")); // Output: false
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)