Odd behavior with cards

I am getting a syntax error that I cannot solve. 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>

      

+3


source to share


3 answers


You have 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 raw Map

, you cannot use Map.Entry<String, String>

in a loop (you can only use raw Map.Entry

).

+4


source


You need to use Generics to avoid this type of conflicts ie

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

      

Generics provides type safety. And besides, I found in your code that your class name was not following best practices. It really should start with the letter "Capital" as the best practice is that the whole JAVA world follows



try it

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 :)

+1


source


because you created
Map map1 = new HashMap();


can be of any type (not just strings), so java doesn't let you downgrade it.

0


source







All Articles