user3427540
user3427540

Reputation: 1172

Odd behavior with Maps

I am getting a syntax error which I am not able to resolve. I am using Java 1.8.

import java.util.*;

public class datatypetest 
{
    public static void main(String args[])
    {
        Map map1 = new HashMap();
        map1.put("1", "Deepak");
        map1.put("2", "Ajay");
        System.out.println(map1);
        System.out.println(map1.keySet());


        for (Map.Entry<String, String> entry : map1.entrySet())
        {
            System.out.println(entry.getKey() + "/" + entry.getValue());
        }

    }
}

But I am getting this error:

incompatible types: Object can not be converted to Entry<String,String>

Upvotes: 3

Views: 81

Answers (3)

Kishore Kumar Korada
Kishore Kumar Korada

Reputation: 1264

You need to use Generics to avoid such Type of Conflicts i.e

Map<String, String> map1 = new HashMap<String, String>();

Generics provides Type Safety. And in addition I've found in your code that your Class name didn't follow best practices. It indeed must start with Capital letter since it's a best practice entire JAVA world follows

Try This

import java.util.*;
public class DataTypeTest {
   public static void main(String args[]){
       Map<String, String> map1 = new HashMap<String, String>();
       map1.put("1", "Deepak");
       map1.put("2", "Ajay");
       System.out.println(map1);
       System.out.println(map1.keySet());

       for (Map.Entry<String, String> entry : map1.entrySet())
       {
           System.out.println(entry.getKey() + "/" + entry.getValue());
       }

   }
}  

Happy Programming :)

Upvotes: 1

prsutar
prsutar

Reputation: 429

because you have created
Map map1 = new HashMap();
can be of any type(not just string) so java is not allowing you to downcast it.

Upvotes: 0

Eran
Eran

Reputation: 393811

You created a raw map :

Map map1 = new HashMap();

Change it to:

Map<String,String> map1 = new HashMap<String,String>();

If you instantiate the map as a raw Map, you can't use Map.Entry<String, String> in the loop (you can only use the raw Map.Entry).

Upvotes: 4

Related Questions