How to remove warnings java
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 ?
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
Why not just use a for loop, as the answer with 72 upvotes suggests.
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).
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.
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)
精彩评论