Should i return List or ArrayList

后端 未结 4 863
时光取名叫无心
时光取名叫无心 2020-12-31 10:41

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 implication

4条回答
  •  无人及你
    2020-12-31 11:41

    For types like List or ArrayList there shouldnt be any compilcation and your should return List promoting Code to an interface.

    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.

    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.

提交回复
热议问题