LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java Output Questions · Question 16

Which keys land in the same hash bucket Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        int buckets = 8;
        Map<Integer, List<Integer>> table = new TreeMap<>();
        for (int key : new int[]{3, 11, 19, 4, 12, 27, 8})
            table.computeIfAbsent(Integer.hashCode(key) % buckets, b -> new ArrayList<>()).add(key);
        System.out.println(table);
    }
}
  • A {3=[3], 4=[4], 8=[8], 11=[11], 12=[12], 19=[19], 27=[27]}
  • B {0=[8], 3=[3, 11, 19], 4=[4, 12], 7=[27]}
  • C {0=[8], 3=[27, 19, 11, 3], 4=[12, 4]}
  • D {0=[8], 3=[3, 11, 19, 27], 4=[4, 12]} Correct
Correct Answer: Option D

An Integer's hash code is its value, and 3, 11, 19 and 27 all leave remainder 3 when divided by 8 – four keys in one chain.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links