Cole
Cole

Reputation: 359

Why is HashMap#get Returning an Object Rather than a String?

This code prints IS STRING which means that that map value is a String.

if(mymap.get("name") instanceof String ) {
    System.out.print("IS STRING");
}

So why does String newName = mymap.get("name"); throw the error Type mismatch: cannot convert from Object to String.

This is what I used to initialize the map where textName.getText() is a string entered in a java swing GUI:

Map<String,String> mymap = new HashMap<String,String>(10);
mymap.put("name", textName.getText()); 

This is the relevant code:

public void actionPerformed(ActionEvent evt){
    Map<String,String> mymap = new HashMap<String,String>(10);
    mymap.put("name", textName.getText());

    makeDocx(mymap);
}

public static void makeDocx(Map mymap) {
    String newName = mymap.get("name");
    textReplace(oSelection, "[Name]", newName, oWord);
}

Upvotes: 0

Views: 1337

Answers (1)

Justin
Justin

Reputation: 25327

Your problem is with this method:

public static void makeDocx(Map mymap) {
    String newName = mymap.get("name");
    textReplace(oSelection, "[Name]", newName, oWord);
}

The replacements is declared as a Map, which is the same as Map<Object, Object>. What you want is to change that to Map<String, String>:

public static void makeDocx(Map<String, String> mymap) {
    String newName = mymap.get("name");
    textReplace(oSelection, "[Name]", newName, oWord);
}

As a general rule, if you are using an object that uses Generics, but not declaring what types you are using, something is wrong. A good IDE, such as Eclipse or Netbeans, will put a warning under Map replacements, saying that you should add the types.


As a side note, you might wonder why you would want to do Map<String, String> replacements, rather than Map replacements with String newName = (String) replacements.get("name");. Imagine if you called the method makeDocx, but you passed it a Map<String, Integer> on accident. This will result in the program trying to cast an Integer to a String, which is impossible. And we like to avoid errors as much as we can, so we should make sure that we force the map to be a Map<String, String>.

Upvotes: 2

Related Questions