开发者

Interface method agruments Arrays vs util List

I am writing an interface and and its implementation. The interface has a method like

doSomething(String[] strs, Integer[] ints, String msg);

I declared parameters as arrays simply because it will call to an external interface having similar arguments. Some people suggest that doSomething a开发者_Python百科gruments should be util List instead of arrays. But I couldn't find any best practice explains the reason reason why util List is preferable?

Loc


Lists are easier to work with, as they have a richer API, and a variety of implementations. So, the upshot is that it's generally more flexible and maintainable.

Josh Bloch's Effective Java highlights one other reason to prefer Lists: "invariance". Generics are checked at compile time, so typed lists will actually catch more errors than arrays:

// Fails at runtime!
Object[] objectArray = new Long[1];
objectArray[0] = "I don't fit in"; // Throws ArrayStoreException
// Won't compile!
List<Object> ol = new ArrayList<Long>(); // Incompatible types
ol.add("I don't fit in");

So, in some instances it's actually safer to use Lists over Arrays.

There's more to it than that, but it starts getting difficult to explain. See this link to the relevant section of Effective Java, ch 5: http://java.sun.com/docs/books/effective/generics.pdf

HTH


Basically list is abstract type and it need to be implemented again by any of its family members like ArrayList etc. So there is no much difference in using array and list in regarding performance, both are identical. Only in terms of maintainability we go for List interface and we can implement it for any family of List interface later based on the requirement.Also list provide flexible operations over array.


This falls under maintainability. You will find it very convenient to use the methods prepared for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜