Specifying the return type of the iterator.next () method to a character class

I am trying to display the content of the following HashMap file:

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

      

I used the following method to print the content:

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 type casting method:

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

      

but that won't work either. Any help is greatly appreciated. Thank..

+3


source to share


3 answers


Replace the parameter Iterator

and use keySet

:

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

      



Explanation

  • An iterator is a generic type and must be parameterized. This way you call next

    without having to cast from Object

    to the type you want .
  • The call entrySet

    will return Set<Entry<Character, Integer>>

    , which unnecessarily complicates your life if you repeat keys
+5


source


From hm.entrySet()

you are trying to get Set<Character,Integer>

notSet<Character>

Better to use keySet()

. Because it will return Set<K>

(here Key is Character. So it returns Set<Character>

):



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

      

0


source


Try with this code

  Iterator it = hm.entrySet().iterator();
     while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Character key = (Character)entry.getKey();
            Integer value = (Integer)entry.getValue();
         System.out.println("key : "+key+"value : "+(Integer)hm.get(key));
        }

      

And why are you getting an error on that line Character key = new Character(iterator.next());

?, you are passing an int value to the constructor of the Wrapper class. It won't allow it.

All wrapper classes have constructors that can be used to create corresponding objects of the Wrapper class, passing in either a String or a variable of the same data type as the type that the wrapper class corresponds to, with the exception of the character wrapper class whose object cannot be created with String.

0


source







All Articles