如何从Java List中获取一种类型的所有实例?

时间:2012-06-09 10:15:47

标签: java generics

我的代码中有一些部分看起来像这样:

A, B and C extend D

public ArrayList<A> getA() {
    ArrayList<A> allElements = new ArrayList<A>();
    for (D el : listOfDs) {
        if (el instanceof A) {
            allElements.add((A) el);
        }
    }
    return allElements;
}

public ArrayList<B> getB() {
    ArrayList<B> allElements = new ArrayList<B>();
    for (D el : listOfDs) {
        if (el instanceof B) {
            allElements.add((B) el);
        }
    }
    return allElements;
}

public ArrayList<C> getC() {
    ArrayList<C> allElements = new ArrayList<C>();
    for (D el : listOfDs) {
        if (el instanceof C) {
            allElements.add((C) el);
        }
    }
    return allElements;
}

我想将所有这些方法组合成一个这样的方法:

public <T> ArrayList<T> get() {
    ArrayList<T> allElements = new ArrayList<T>();
    for (D el : listOfDs) {
        if (el instanceof T) {
            allElements.add((T) el);
        }
    }
    return allElements;
}

这在Java中是否可行?

目前我

  

无法对类型参数T执行instanceof检查。请改用   它的擦除对象,因为进一步的通用类型信息将   在运行时删除

  

类型安全:从节点到T

取消选中

然后我试过这个:

@SuppressWarnings("unchecked")
public <T> ArrayList<T> get(Class<T> clazz) {
    ArrayList<T> allElements = new ArrayList<T>();
    for(D o : listOfDs) {
        if (o.getClass() == clazz) {
            allElements.add((T) o);
        }
    }
    return allElements;
}

它不会抛出任何错误,但我怎么称呼它?这不起作用:

get(A);

1 个答案:

答案 0 :(得分:5)

你可以使用Guava的Iterables.filter

使用示例:

Iterable<X> xs = Iterables.filter(someIterable, X.class);

由于它是一个开源库,您可以查看源代码以找到您所做的错误。