Common Ancestor to Java Array and List

Phương Nguyễn picture Phương Nguyễn · Mar 14, 2010 · Viewed 10.4k times · Source

In .NET, both array and list have Enumerable as ancestor, so a method that accept Enumerable as an argument can receive both array and list as its argument. I wonder if there is a similar thing in Java?

Answer

Jon Skeet picture Jon Skeet · Mar 14, 2010

No, there's no equivalent in Java. I would generally suggest that you design API methods to receive List<T>, Collection<T> or Iterable<T>. While these preclude directly calling the method with an array, you can wrap an array very easily using Arrays.asList. This is more flexible for the caller than specifying an array as a method parameter, which forces a single implementation.

I agree it's not ideal though.

Note that in .NET, single-dimensional arrays don't just implement IEnumerable<T> - they implement IList<T> as well.