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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs