James
James

Reputation: 101

Java, getting object from map iterator and then invoking methods?

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

Answers (4)

Bozho
Bozho

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

Sean Patrick Floyd
Sean Patrick Floyd

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:

  • if you just want the keys, use map.keySet()
  • if you just want the values, use map.values()
  • use map.entrySet() only if you need the complete mapping

Upvotes: 1

duffymo
duffymo

Reputation: 308763

Try it this way if you're using JDK 6:

for (Apple apple : applesMap.values())
{
    // process apple here.
}

Upvotes: 2

Bala R
Bala R

Reputation: 108957

Try casting the value

Apple a = (Apple) entries.getValue();
a.beDelicious();

Upvotes: 1

Related Questions