1

I was solving a question on finding the duplicates in an array. I made use of a HashMap. but the getValue() function gave me an error when I included it within an IF condition.

for(Map.Entry m : hm.entrySet())
{  
   if(m.getValue() > 1)
   {
      System.out.println(m.getKey());
   }  
}

however it seems to work fine when I used typecasting

for(Map.Entry m : hm.entrySet())
{ 
    int count = (int)m.getValue();  
    if(count > 1)
    {
        System.out.println(m.getKey());
    }  
}

Why did this happen?

Yannick
  • 813
  • 8
  • 17
batman007
  • 39
  • 2
  • 9

1 Answers1

4

Why did this happen?...

because you are using an Entry with raw types...

your Map.Entry must match the map type in the generic type K,V

example: if you define a map of the form

Map<String, Integer> hm = new HashMap<>();

then you can do

for (Entry<String, Integer> m : hm.entrySet()) {
    if (m.getValue() > 1) {
        System.out.println(m.getKey());
    }
}

bacause doing this m.getValue() > 1 automatically unbox the Integer into an int making valid the comparison against the literal int 1

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97