1

I found this and it seems to be working, I'm trying to iterate trough HashMap :

Iterate through a HashMap

But this portion of code shows warnings and I don't have a clue how to make it not show them :

Iterator it = map.entrySet().iterator();
Map.Entry pairs = (Map.Entry) it.next();

Is there a way to "fix" this without using suppressWarnings annotation ?

Community
  • 1
  • 1
London
  • 14,986
  • 35
  • 106
  • 147

5 Answers5

7

Yes, use the correct generic definitions of it and pairs - assuming map is correctly defined.

For example:

Map<String, Integer> map = ...;
Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
Map.Entry<String, Integer> pairs = it.next();  // no need for cast
dty
  • 18,795
  • 6
  • 56
  • 82
1

Why not just use a for loop, as the answer with 72 upvotes suggests.

Michael Younkin
  • 788
  • 6
  • 11
0

I'm assuming the warnings you're getting, you'll want something like this I think:

Iterator<Map.Entry> it = map.entrySet().iterator();
Map.Entry pairs = it.next();

The warnings are being given because you're not specifying the type of what the Iterator is iterating over, therefore it might be an unsafe cast when you cast it to Map.Entry. Specifying the type means the compiler can ensure that things are of the expected type (in which case you don't even need to perform the cast).

Melv
  • 2,201
  • 16
  • 14
  • That'll just get you a warning/cast when you try and use `pairs` – dty Mar 22 '11 at 22:49
  • @dty While that's true, without that code having been posted I can't really fix it and post what it should be. I'm hoping the above illustrates the concept, and then the poster can figure out how the rest of the code shoudl work. – Melv Mar 22 '11 at 22:50
0

Another simple solution is to create two Arrays of Strings of the same size... one that keeps keys, the other keeps values... Keep them in the right order, and you can use a for loop to get the keys and value for any index.

Granted, it's not as fancy as getting the keys from the map and using the iterator... But it works.

It Grunt
  • 3,300
  • 3
  • 21
  • 35
0

Firstly you should better declare your Map:

Map<String, Object> map = ...

If you declare in this way then you will be able to use map.entrySet() which return you Set with Map.Entry elements (without any warnings)

lukastymo
  • 26,145
  • 14
  • 53
  • 66