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>
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).
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With