开发者

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

开发者 https://www.devze.com 2023-03-02 03:30 出处:网络
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 m

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.ge开发者_C百科tKey() + " = " + entries.getValue());
    //Apple a = entries.getValue(); 
} 


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

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


Try casting the value

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消