例外是在ListCreator我的“何时”方法行中添加t 你们可以告诉我为什么我会收到这种例外情况吗? Intelij在语法和逻辑上看不到任何错误,那么怎么了? 我想做自己的映射器和选择器(过滤器),而且我一直都这样。这里有什么问题吗? 您能否看到可能导致这种情况的原因? 我需要使用泛型,否则我会迷路。
package zad1;
import java.util.*;
public class ListCreator<T> {// Uwaga: klasa musi być sparametrtyzowana
List<T> list;
protected ListCreator(List<T> listcreate){
this.list = listcreate; //kreator robi nowa liste zeby nie modyfikowac
}
public static <T> ListCreator<T> collectFrom(List<T> srclist){
ListCreator<T> listCreator = new ListCreator<>(srclist);
return listCreator;
}
public ListCreator<T> when(Selector<T> selector){
List<T> nextlist = new ArrayList<>();
for (T t: this.list){
if (selector.select(t)){
this.list.add(t); //dla kazdego elementu list ktoremu kolejno odpowiada t, jesli spelnia warunek to element jest dodawany do nowej listy
}
}
this.list = nextlist;
return this;
}
public <S> List<S> mapEvery(Mapper<T,S> map){
List<S> dlist = new ArrayList<>();
for (T arg: this.list){
dlist.add(map.map(arg));
}
return dlist;
}
}
package zad1;
import java.util.*;
public class Main {
public Main() {
List<Integer> src1 = Arrays.asList(1,7,9,11,12);
System.out.println(test1(src1));
List<String> src2 = Arrays.asList("a", "zzzz", "vvvvvvv");
System.out.println(test2(src2));
}
public List<Integer> test1(List<Integer> src) {
Selector <Integer> sel = new Selector<Integer>() {
@Override
public boolean select(Integer arg) {
return arg < 10;
}
};
Mapper <Integer,Integer> map = new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer arg) {
return arg + 10;
}
};
return ListCreator.collectFrom(src).when(sel).mapEvery(map);
}
public List<Integer> test2(List<String> src) {
Selector <String> sel = new Selector<String>() {
@Override
public boolean select(String arg) {
if (arg.length() > 3)
return true;
else
return false;
}
};
Mapper <String, Integer> map = new Mapper<String, Integer>() {
@Override
public Integer map(String arg) {
return arg.length() + 10;
}
};
return ListCreator.collectFrom(src).when(sel).mapEvery(map);
}
public static void main(String[] args) {
new Main();
}
}