Should i return List or ArrayList

后端 未结 4 849
时光取名叫无心
时光取名叫无心 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:27

    The only reason to return concrete class could be if caller needs to be aware of this concrete implementation or, possibly, additional interfaces on concrete implementation. For example, in Android, you often have to use ArrayList because framework does not know how to properly serialize generic list interface.

    0 讨论(0)
  • 2020-12-31 11:39

    Implication is that you wont be able to call methods of ArrayList that are not methods of List interface for the objects returned.

    But if the object is an ArrayList you can do a cast.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 11:45

    It's best to return the most generic type that's appropriate for your interface.

    If there's some reason why ArrayList is inherently appropriate for the data you're returning then you should use that. Typically List is fine but you might also consider using Collection if the returned values are inherently unordered:

    Diagram of Java collections hierarchy

    0 讨论(0)
提交回复
热议问题