Bird
Raised Fist0

Consider this Menu class snippet:

medium📝 Analysis Q7 of Q15
LLD - Design — Food Delivery System
Consider this Menu class snippet:
class Menu {
  Map items = new HashMap<>();
  void addItem(String name, double price) {
    items.putIfAbsent(name, price);
  }
}

What will happen if addItem is called twice with the same dish name but different prices?
AThe price is updated to the second inserted price
BThe price remains the first inserted price; second call is ignored
CAn exception is thrown on the second call
DBoth prices are stored as separate entries
Step-by-Step Solution
Solution:
  1. Step 1: Understand putIfAbsent behavior

    putIfAbsent inserts the key-value only if the key is not already present.
  2. Step 2: Effect of calling addItem twice with same name

    The first call inserts the price; the second call does nothing since key exists.
  3. Final Answer:

    The price remains the first inserted price; second call is ignored -> Option B
  4. Quick Check:

    putIfAbsent ignores duplicate keys [OK]
Quick Trick: putIfAbsent prevents overwriting existing keys [OK]
Common Mistakes:
MISTAKES
  • Assuming price updates on second call
  • Expecting an exception on duplicate keys

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes