returning a hashmap in java

Move your definition of dict and your return statement out of the loop, and it should be fine (the first one before entering, the last one after exiting the loop).

In your current code, the return statement is not guaranteed to be reachable (i.e. if your loop is not even entered), which has to be given in a non-void function.

Additionally, your method would call return in each hypothetical iteration, which means your method will always end with the first iteration. A return leads to function exit, no matter what comes after, which means your code would not work as you’d expect. Additionally, you’d create multiple HashMaps, as you call the constructor once per iteration.

public HashMap<Integer, Character> dataset(String text) {

    HashMap<Integer, Character> dict = new HashMap<Integer, Character>();

    for (int i = 0; i < text.length(); i++) {
        char value = text.charAt(i);
        dict.put(i,  value);

    return dict; // Here's the error

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top