Search code examples
javaenumerable

Common Ancestor to Java Array and List


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?


Solution

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