如何在Java中迭代向量并仅存储指定的类? [英] How to iterate over the vector in Java and store only the specified class?

查看:131
本文介绍了如何在Java中迭代向量并仅存储指定的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我需要迭代 Vector 元素并将结果存储在say数组中,只要该实例是类方法

I have a use case where I need to iterate over the Vector elements and store the results in say array only if that instance is of class method

有什么容易做到的吗?

Are there any easy to do this?

目前我这样做:

    Iterator itr = vec.iterator();
    Iterator element = vec.iterator();

    while(itr.hasNext())
    {
        boolean method = itr.next() instanceof Method;
        if(method)
            System.out.println( "\t" + ( (Method)(element.next()) ).name);
        else
            element.next();
    }

但我认为会有更好的方法。

But I think there will be some better way than this.

推荐答案

假设您有一个类方法,那么代码可能是这样的:

Assume you have a class Method, then code could be something like :

    List<Method> list = new ArrayList<Method>();
    for (Object obj : vector) {
        if (obj instanceof Method) {
            list.add(obj);
        }
    }

这篇关于如何在Java中迭代向量并仅存储指定的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆