Iterator it = myHashMap.keySet().iterator();
while (it.hasNext()) {
int next = it.next();
}
That doesn't work because it.next() returns Object. My hashmap uses ints for keys. All of my methods ac开发者_如何学Gocept ints to access the hashmap. How can I actually get an int value when looping through my keys so I can pass it to my other methods?
You should use generics.
Map<Integer, Object> myHashMap;
This gives you keys that are Integer (not int, but that cannot be helped). Integer can be automatically unboxed:
for (int key : myHashMap.keySet()){
}
If you want your keys in ascending order, consider using TreeMap
instead of HashMap
.
First of all try to use Generics while defining your Map
/HashMap
. Then you don't need to worry.
Second thing, HashMap doesn't use primitive type for keys. Which means you are mistaken, and the actual type used as keys is Integer
, not int
.
A quick fix can be a cast to int
, like below
int next = ((Integer) it.next()).intValue();
A detailed example, with a new loop syntax (introduced in Java 5).
Map<Integer, String> map = new HashMap<Integer, String>();
...
for(int n : map.keySet()) {
...
}
You should use Java generics:
Map<Integer, Object> myHashMap = new HashMap<Integer, Object>();
// ...
for (int key : myHashMap.keySet()) {
// ...
}
HashMaps in Java can only use objects, not primtives.
So it is more likely that your keys are of type Integer, and that when you put stuff in, it gets promoted from int to Integer.
All that being said, this is really old school Java. Your collection should define the key and target type using generics, and there's also a for-each in Java for(Integer key: myHashMap.keySet())
BTW: be aware that there are no guarantees about the order in which you'll be iterating.
Your int
s are autoboxed into Integer
s when you use them as keys in Map
s.
As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.
I'm not sure if your key array is all you need, but I typically loop through maps like this:
Map<Integer, Object> map = new HashMap<Integer, Object>();
for(Map.Entry<Integer, Object> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey());
System.out.println("Value: " + entry.getValue());
}
The answer is simple: Use generic Iterator as below.
Iterator<Integer> it = myHashMap.keySet().iterator(); while (it.hasNext()) { int next = it.next(); }
精彩评论