如何从集合中返回对象?

时间:2018-11-22 15:29:26

标签: java

给出一个集合,如何知道该集合的索引i,从该集合返回一个对象?

我不能使用“ get”方法,那我该怎么用?

public static void remove(Collection coll, Predicate pred) {
    for(int i=0; i<coll.size(); i++) {
        if(pred.test(coll.get(i))) {
            coll.remove(i);
        }
    }
}

错误:未为Collection类型定义get(int)方法

2 个答案:

答案 0 :(得分:0)

Java的Collection没有get()这样的方法。使用迭代器:

    Iterator<Object> iterator = coll.iterator();
    while (iterator.hasNext()) {
        // Your code here
    }

答案 1 :(得分:0)

您可以尝试一下。

nodemailer