Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecasting the return type of iterator.next() method to Character class

Tags:

java

hashmap

I am trying to display the contents of the following HashMap :

 HashMap<Character,Integer> hm = new HashMap<Character,Integer>();

I have used the following method to print out the contents :

Set hmset = hm.entrySet();
Iterator iterator = hmset.iterator();
while(iterator.hasNext())
    {
    Character key = new Character(iterator.next());
    System.out.println("key : "+key+"value : "+(Integer)hm.get(key));
}

I am getting the following error :

error: constructor Character in class Character cannot be applied to given types;

I have also tried the following way of type casting :

Character key = (Character)iterator.next();

but that would'nt work either. Any help greatly appreciated. Thanks..

like image 340
kajfhk Avatar asked Nov 23 '25 05:11

kajfhk


1 Answers

Parametrize your Iterator and use keySet:

Iterator<Character> iterator = hm.keySet().iterator();

Explanation

  • Iterator is a generic type and should be parametrized. This way, you invoke next without having to cast from Object to your desired type.
  • Invoking entrySet will return a Set<Entry<Character, Integer>>, which complicates your life unnecessarily if you're iterating the keys
like image 73
Mena Avatar answered Nov 24 '25 19:11

Mena



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!