user5268786
user5268786

Reputation:

Why HashMap produced output 0 for this program?

I do not understand how this java program is showing the output as zero. I believe it should be 1. Per my knowledge it doesn't allows the same key to be used more than once. Can someone please explain this thoroughly ?

import java.util.HashMap;
import java.util.Map;

public class Names {
    private Map<String, String> m = new HashMap<>();

    public void names(){
        m.put("Mickey", "Mouse");
        m.put("Mickey", "Mouse");
    }
    public int size(){
        return m.size();
    }
    public static void main(String[] args) {
        Names names = new Names();
        System.out.println(names.size());
    }
} 

Output: 0

Upvotes: 0

Views: 125

Answers (2)

Vivek Kumar
Vivek Kumar

Reputation: 11

In your code

public void names(){
    m.put("Mickey", "Mouse");
    m.put("Mickey", "Mouse");
}

is not a constructor of your java class. You should define it like

public Names(){
    m.put("Mickey", "Mouse");
    m.put("Mickey", "Mouse");
}

Read this link : https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Upvotes: 0

simon
simon

Reputation: 1105

The problem is that the method you've written to add objects to the HashMap is never being ran, you probably meant to do one of the below things:

public void names(){
    m.put("Mickey", "Mouse");
    m.put("Mickey", "Mouse");
}

needs to be

public Names(){
    m.put("Mickey", "Mouse");
    m.put("Mickey", "Mouse");
}

or

public static void main(String[] args) {
    Names names = new Names();
    System.out.println(names.size());
}

needs to be

public static void main(String[] args) {
    Names names = new Names();
    names.names();
    System.out.println(names.size());
}

Upvotes: 3

Related Questions