类型安全,通用,空集合与静态泛型 [英] Type-safe, generic, empty Collections with static generics

查看:109
本文介绍了类型安全,通用,空集合与静态泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尽可能返回空集合与null。我可以使用 java在两种方法之间切换.util.Collections

I return empty collections vs. null whenever possible. I switch between two methods for doing so using java.util.Collections:

return Collections.EMPTY_LIST;
return Collections.emptyList();

其中 emptyList()类型安全。但我最近发现:

where emptyList() is supposed to be type-safe. But I recently discovered:

return Collections.<ComplexObject> emptyList();
return Collections.<ComplexObject> singletonList(new ComplexObject());

等。

在Eclipse包资源管理器中:

I see this method in Eclipse Package Explorer:

<clinit> () : void

但我不知道如何在源代码。

but I don't see how this is done in the source code (1.5). How is this magic tomfoolerie happening!!

编辑:
如何实现静态泛型类型?
$ b

推荐答案


编辑:如何实现静态泛型类型

How is the static Generic type accomplished?

http ://www.docjar.com/html/api/java/util/Collections.java.html

public class Collections {
    ...
    public static final List EMPTY_LIST = new EmptyList<Object>();
    ...
    public static final <T> List<T> emptyList() {
        return (List<T>) EMPTY_LIST;
    }
    ...
}

链接来实现EmptyList类,如果你好奇,但对你的问题,这没关系。

You can see the link for the implementation of the EmptyList class if you're curious, but for your question, it doesn't matter.

这篇关于类型安全,通用,空集合与静态泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆