Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 381
user3427540 Avatar asked May 07 '26 07:05

user3427540


2 Answers

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

like image 196
Eran Avatar answered May 09 '26 02:05

Eran


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

like image 35
Kishore Kumar Korada Avatar answered May 09 '26 03:05

Kishore Kumar Korada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!