1

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

Sam
  • 1,501
  • 3
  • 19
  • 27
Loc Phan
  • 3,854
  • 3
  • 26
  • 34
  • 2
    This is a good discussion on [Array vs List in java](http://stackoverflow.com/questions/716597/array-or-list-in-java-which-is-faster). – Harry Joy May 23 '11 at 04:52

3 Answers3

1

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

laher
  • 8,102
  • 3
  • 27
  • 37
0

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.

developer
  • 9,003
  • 29
  • 80
  • 144
0

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

setzamora
  • 3,302
  • 5
  • 31
  • 45