Fetching an iterator for a HashMap throws a cast exception

I have some relatively simple code that I did that was supposed to get an iterator for a HashMap and print out the values โ€‹โ€‹of a key pair .

My problem is that when I go to get an iterator, I get this exception.

Exception in thread "main" java.lang.ClassCastException: java.util.HashMap $ Record cannot be passed to java.lang.String
in Delete.main (Delete.java:25)

Here is my code, and I indicate where line 25 is:

Map <String, UpdatablePage> contentMap = new HashMap <String, UpdatablePage>(); contentMap.put( "test", new UpdatablePage() ); for ( Iterator it = (Iterator) contentMap.entrySet().iterator(); it.hasNext(); ) { String key = (String) it.next(); // LINE 25 UpdatablePage value = contentMap.get(key); System.out.print( "Key=" + key + ", Value=" + value.toString() ); } 

PS, I tried iterating over the map using Map.Entry, but when I go to return the value returned by the iterator to Map.Entry, I get another casting exception, why?

 // Error occurs when I do the following Map.Entry pair = (Map.Entry) it.next(); 
+4
source share
3 answers

In this line: for (Iterator it = (Iterator) contentMap.entrySet (). Iterator (); it.hasNext ();)

entrySet () should be keySet () - your iterator returns every record, but as you send them to String, I assume that these are the keys you need.

+4
source

When re- Map.Entry records, you return Map.Entry objects, after which you can use getKey() and getValue() to retrieve the key and value. There is no need to iterate over the keys and separately extract the value (which is much less efficient).

By the way, you should not pass the Map.Entry iterator, but the object that the iterator returns at each iteration.

+2
source

Use keySet () and a generic iterator for best results:

  Map<String, UpdatablePage> contentMap = new HashMap<String, UpdatablePage>(); contentMap.put("test", new UpdatablePage()); for (Iterator<String> it = contentMap.keySet().iterator(); it.hasNext();) { String key = it.next(); UpdatablePage value = contentMap.get(key); System.out.print("Key=" + key + ", Value=" + value.toString()); } 

There is no need for any casts with the general iterator, and you get the advantage of checking the type of compilation time rather than excluding the runtime, as you can see.

+1
source

Source: https://habr.com/ru/post/1340575/


All Articles