2013-01-14 65 views
1

如何返回一个使用泛型作为空列表的自定义对象?返回一个通用空列表

我已经扩展了List接口,并创建了自己的自定义类型

public interface MyCustomList<T> 
    extends List<T> 
{ 

在一个类中,我有它返回一个自定义列表的方法,但我总是一个编译器错误告终。基本上这个方法的默认实现应该返回一个空列表,但我不能让它工作,因为我遇到了下面的错误。 “不兼容类型”

public MyCustomList<MyCustomBean> getCodes(String code) 
{ 
    return Collections.<MyCustomList<MyCustomBean>>emptyList(); 
} 

请告诉我发回一个“泛型”空单执行的正确方法?

+0

为什么你需要一个自定义的List接口? –

+2

不是答案,而是解释:你不能这样做的原因是因为Collections.emptyList()的签名是'列表 emptyList()'。这意味着它将返回一个T列表。当你像这样调用'emptyList()'时,它实际上会返回'List >',但是'getCodes()'方法会返回一个' MyCustomList '所以你得到一个编译时错误。 –

回答

2

敷衍impl有什么问题吗?

class MyCustomListImpl<T> extends ArrayList<T> implements MyCustomList<T> {} 

return new MyCustomListImpl<MyCustomBean>(); 
+0

'MyCustomList'只是界面。在你的决定中,你将不得不在'return'语句的匿名类中实现所有'List'接口。 – Andremoniy

+0

@Andremoniy oops - 没有注意到。固定。 :) – Bohemian

+0

去了这个答案,但其他答案对我也很酷..谢谢! –

0

在你的情况下,这是不可能的,直到你将有适当的实现你的接口MyCustomList

UPD:Collections.emptyList()收益专项实施List接口,这当然是无法转换为您MyCustomList的。

+0

是的,铸造无法工作,因为我遇到'不可兑换的类型'.. –

2

Collections.emptyList返回List<T>,其实现hidden。由于您的MyCustomList接口是分机List,因此无法在此处使用此方法。

为了这个工作,你需要做的空MyCustomList的实现,以同样的方式,核心API的Collections实现空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; 
    } 
} 
0

不能使用Collections.emptyList()用于此目的。这是类型安全的,似乎做你正在寻找!

+0

这不会工作..编译时错误。 –

+0

不,我的意思是不使用自定义接口(MyCustomList),只使用方法原型中的实际类型。在你想返回空列表的地方,简单的使用Collections.emptyList()。是否有理由定义自己的界面? – Nrj