使用来自Guava的Iterables的ClassCastException

Dev*_*ips 2 java android guava

我试图使用Iterables类来过滤ArrayList,但是当我尝试将结果转换回原始类型时,我在运行时获得了ClassCastException.

// domains is an ArrayList<Domain> which is defined earlier in the class
Iterable<Domain> temp = Iterables.filter(domains, new Predicate<Domain>() {
    public boolean apply(Domain input) {
        if (input.getName().toLowerCase().contains(filter.toString().toLowerCase())) {
            return true ;
        } else {
            return false;
        }
    }
}) ;
ArrayList<Domain> filteredDomains = (ArrayList<Domain>) temp ; // Error occurs here
Run Code Online (Sandbox Code Playgroud)

为了完成,我试图在目标为1.6的Android应用程序中使用它.

Joa*_*uer 8

temp不是ArrayList<Domain>.这是一个Iterable<Domain>.

如果你绝对 需要一个ArrayList<Domain>(或List<Domain>一般),那么你就需要采取一种不同的方法.

首先,使用Collections2.filter()而不是Iterables.filter():生成temp然后ArrayList从结果中创建一个新的Collection:

Collection<Domain> temp = Collections2.filter(domains, myPredicate) ;
List<Domain> filteredDomains = new ArrayList<Domain>(temp);
Run Code Online (Sandbox Code Playgroud)

但你应该真的想想,如果你需要一个List或者ArrayList如果一个Collection是不够你想要的东西.如果a Iterable足够(例如,如果您只迭代内容),那么您甚至可以继续使用Iterables.filter().