简体   繁体   中英

Pre-generics, cast object from hashmap?

How do I iterate through a hashmap (containing objects of type Person) and calling methods on the Person object?

I used:

for(Iterator it = hashmap.entrySet().iterator(); is.hasNext();){
    Person p = (Person)it.next();
    p.doSomething();
}

but when the Person cast is being performed it says the object cannot be cast to a Person object (however it definitely is a subtype of Person).

java.util.HashMap$Entry cannot be cast to Person.

EDIT this is 1.4!

由于迭代器将遍历Map.Entry对象,因此请首先将它们提取为这些类型:

Person p = (Person)((Map.Entry)it.next()).getValue();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM