Reputation: 101
I have a map and this contains objects, lets say of type 'Apple'. I currently have an iterator but the only thing I seem to be able to call is the getKey and getValue. getValue seems to return the memory address of the actual Apple object, but i wanted to be able to do Apple a = Map.Entry.getValue()
i can only seem to get the key and memory address :s
Iterator it = ApplesMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entries = (Map.Entry)it.next();
System.out.println(entries.getKey() + " = " + entries.getValue());
//Apple a = entries.getValue();
}
Upvotes: 0
Views: 382
Reputation: 597076
Use generics:
Map<String, Apple> map = ....;
if you need the key:
for (Map.Entry<String, Apple> entry : map.entrySet()) {..}
if you don't need the key:
for (Apple apple : map.values()) {..}
Since you had a sub-question in one of the comments: Under the hood the for-each loop uses the Iterator
. Every Iterable
class is eligible for a for-each loop. But you are not bothered with operating the iterator - it is operated automatically for you. An Iterator
is still useful if you want to call remove()
on it.
Upvotes: 1
Reputation: 298888
This is ancient code. Use Generics and for-each loops.
Map<String, Apple> map = // create map here
for(Map.Entry<String, Apple> entry : map.entrySet()){
Apple thisIsAnApple = entry.getValue();
String andThisIsTheKeyThatLinksToIt = entry.getKey();
}
BTW:
map.keySet()
map.values()
map.entrySet()
only if you need
the complete mappingUpvotes: 1
Reputation: 308763
Try it this way if you're using JDK 6:
for (Apple apple : applesMap.values())
{
// process apple here.
}
Upvotes: 2
Reputation: 108957
Try casting the value
Apple a = (Apple) entries.getValue();
a.beDelicious();
Upvotes: 1