Collections.emptyList
返回 a List<T>
,其实现是隐藏的。由于您的MyCustomList
界面是 的扩展,List
因此无法在此处使用该方法。
为了让它工作,你需要实现一个 empty MyCustomList
,就像核心 APICollections
实现一个空List
实现一样,然后使用它。例如:
public final class MyEmptyCustomList<T> extends AbstractList<T> implements MyCustomList<T> {
private static final MyEmptyCustomList<?> INSTANCE = new MyEmptyCustomList<Object>();
private MyEmptyCustomList() { }
//implement in same manner as Collections.EmptyList
public static <T> MyEmptyCustomList<T> create() {
//the same instance can be used for any T since it will always be empty
@SuppressWarnings("unchecked")
MyEmptyCustomList<T> withNarrowedType = (MyEmptyCustomList<T>)INSTANCE;
return withNarrowedType;
}
}
或者更准确地说,将类本身隐藏为实现细节:
public class MyCustomLists { //just a utility class with factory methods, etc.
private static final MyEmptyCustomList<?> EMPTY = new MyEmptyCustomList<Object>();
private MyCustomLists() { }
private static final class MyEmptyCustomList<T> extends AbstractList<T> implements MyCustomList<T> {
//implement in same manner as Collections.EmptyList
}
public static <T> MyCustomList<T> empty() {
@SuppressWarnings("unchecked")
MyCustomList<T> withNarrowedType = (MyCustomList<T>)EMPTY;
return withNarrowedType;
}
}