Sponsored Link •
Bill Venners: When should I use a
List versus an array as a return type or parameter type.
Josh Bloch: Darn good question. The equation changes, of course, when we get generics. Right now, if you want to provide a statically typed return value or input parameter, then you have to use an array.
Lists are not statically typed, because they are ordinary old interfaces and there is no way to parameterize a user type these days. Arrays, because they are part of the language, have the distinction of being the only generic type, or parameterized type, in the language. So, if it's very important to you to have static typing, then you must use arrays.
The other thing is that arrays, once again, are fairly traditional. They are less disconcerting to people than
Lists have not been widely adopted yet as the currency for passing stuff in and out.
On the other hand,
Lists are nice. They are very flexible. You can pass anything, including an array, on input if you have an input parameter that's a
List. So, if you are writing something where you really don't know where the input is coming from, then
List makes a nice input type. If someone happens to have an array, they can say
Arrays.asList and pass the array in as a
List. And that doesn't involve a copy. It's a simple wrapping operation with a small, constant cost.
On the other hand, if it will be used in a more tightly defined context and you really would like to have that compile time type safety, so that you don't get a
ClassCastException at run time if you were expecting a
List of mail messages and you got a
List of mail folders, then I think you should use the arrays. Arrays are also likely to be a bit cheaper, but on the other hand, you know how I feel about performance. If it's not a bottleneck, then you might as well do the right thing, rather than the fast thing.
So right now, a lot of people use arrays to get compile time type safety, and they certainly have my blessing until the language has generics. Once you can pass in
List of mail messages and
List of mail folder as two distinct types, then I think it becomes much more reasonable to take the
List on input.
In fact, we haven't really thought hard about this stuff, but I suppose it would even be possible to have arrays implement the
List interface. So that when you take a
List on input, you can also pass an array without even wrapping it. That would be a major change. When we put the collections framework into the platform, we did it without any changes to the language. But I think it might not have been unreasonable to do exactly that, to turn arrays into
You touched on the only two reasonable input types,
List and array. Don't use
Vector on input, don't use
HashTable. They don't cut it. Of course,
Map is okay as well. On output, of course, you can use the other things if you are willing to commit to those types.