我有多个类的集合,我需要一个迭代器,并且该对象已强制转换

时间:2019-03-26 10:54:46

标签: java casting iterator

我有一个ArrayList,并且有不同对象的集合

然后我有一个迭代器


for(Iterator i = results.iterator(); i.hasNext();) {

Object row = i.next();

问题是我有多个使用此类的课程。例如User.class。我如何确保我得到该物体

User u = (User) row?

1 个答案:

答案 0 :(得分:-2)

使用instanceof!

 for(Iterator i = results.iterator(); i.hasNext();) {

    Object row = i.next();

    if (row instanceof User) {
       User u = (User) row; // this is safe
       // ...
    }

 }

具有多种类型

 for(Iterator i = results.iterator(); i.hasNext();) {

    Object row = i.next();

    if (row instanceof User) {
       User u = (User) row; // this is safe
       // ...
    } else if (row instanceof Stuff) {
       Stuff u = (Stuff) row; // this is safe
       // ...
    }

 }

在通用列表中具有多种类型

 Collection<? extends Human> results = ... ;
 for(Human h : results) {

    if (h instanceof User) {
       User u = (User) h; // this is safe
       // ...
    } else if (h instanceof Man) {
       Man m = (Man) h; // this is safe
       // ...
    } else if (row instanceof Woman) {
       Woman w = (Woman) h; // this is safe
       // ...
    }

 }

foreach变体

for (Object row : results) {
    if (row instanceof User) {
       User u = (User) row; // this is safe
       // ...
    }
}

java 8变体

results.stream().filter(row -> row instanceof User).map(row -> (User) row).forEach(user -> {...});

HTH!