LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java – Find the Error · Question 10

Error: adding a String to an Integer adjacency list Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

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

public class Main {
    public static void main(String[] args) {
        Map<String, List<Integer>> g = new HashMap<>();
        g.computeIfAbsent("A", k -> new ArrayList<>()).add("B");
        System.out.println(g);
    }
}
  • A computeIfAbsent cannot create lists
  • B The neighbour lists are List<Integer>, so add("B") passes a String where an Integer is required; declare Map<String, List<String>> Correct
  • C HashMap keys must be Integer
  • D g must be printed with a loop
Correct Answer: Option B

javac: "incompatible types: String cannot be converted to Integer". The key and neighbour types of a graph are usually the same.

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