我应该返回List或ArrayList [英] Should i return List or ArrayList
问题描述
我发现自己同意返回一个界面而不是一个具体的类。
I find myself agreeing to return an interface instead of a concrete class.
原因很简单,我想要松耦合。
The reason is simple, i want loose coupling.
但是会有其他影响或权衡吗?
But will there be other implications or trade off?
推荐答案
对于像List或ArrayList这样的类型,不应该有任何compilcation,你应该返回List促进代码到界面 。
For types like List or ArrayList there shouldnt be any compilcation and your should return List promoting Code to an interface.
你会发现你的自我限制,如果这是来自并发包,如 CopyOnWriteArrayList 你正在使用像 addIfAbsent ,未在List界面中定义。
You will find your self restricted doing so had this been from Concurrency package like CopyOnWriteArrayList and you were using methods like addIfAbsent which is not defined in List interface.
因此,如果您返回ArrayList或任何具体实现,您可以使用未在合同中定义的API( List
接口),但是您受到限制在陈从特定实现到其他东西(从 ArrayList
到 LinkedList
),因为使用您的API的每个人都必须更改为根据你的变化,我认为太多了。
So if you return ArrayList or any concrete implementation for that matter you can use API which are not defined in the contract (List
interface), but then you are restricted in changeing from specific implementation to something else(from ArrayList
to LinkedList
), as everyone using your API will have to change as per your changes, too much to expect I think.
这篇关于我应该返回List或ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!