简体   繁体   中英

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 agruments 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM