这个代码怎么了?它没有过滤集合!

jai*_*jai 0 java generics

public class CollectionsFilter {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6, 7,
                8, 9, 10 });
        Collection<Integer> evenNumbers = Utils.filter(list,
                new Predicate<Integer>() {
                    public boolean apply(Integer i) {
                        if (i % 2 == 0) {
                            return true;
                        }
                        return false;
                    }
                });

        Collection<Integer> oddNumbers = Utils.filter(list,
                new Predicate<Integer>() {
                    public boolean apply(Integer i) {
                        if (i % 2 != 0) {
                            return true;
                        }
                        return false;
                    }
                });
        System.out.println("EVEN Numbers > " + evenNumbers);
        System.out.println("ODD Numbers > " + oddNumbers);
    }

}
Run Code Online (Sandbox Code Playgroud)

我的Utils.filter()方法是:

public static <T> Collection<T> filter(Collection<T> target,
            Predicate<T> predicate) {
        Collection<T> filteredCollection = new ArrayList<T>();
        for (T t : filteredCollection) {
            if (predicate.apply(t)) {
                filteredCollection.add(t);
            }
        }
        return filteredCollection;
    }
Run Code Online (Sandbox Code Playgroud)

和Prdicate:

public interface Predicate<T> {
    public boolean apply(T type);
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*orn 5

首先,不要自己编写这种代码.有谷歌收藏.

话虽如此:尝试迭代target而不是filteredCollection在你的filter()方法中,这应该修复它.