DEV Community

realNameHidden
realNameHidden

Posted on

1 1 1 1 1

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay