Common Ancestor to Java Array and List

后端 未结 6 1933
闹比i
闹比i 2020-12-18 19:54

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 ther

相关标签:
6条回答
  • 2020-12-18 20:01

    Basically, arrays have an implicit type that is a subclass of object. See Arrays in the JLS:

       public static void main(String[] args) {
                int[] ia = new int[3];
                System.out.println(ia.getClass());
                System.out.println(ia.getClass().getSuperclass());
       }
    
       > class [I
       > class java.lang.Object
    

    The way arrays and lists are handled is also not the same when we consider covariance/contravariance.

    List<Object> l = new ArrayList<String>(); // complain 
    Object[] l2 = new String[1]; // ok
    
    l2[0] = 4; // throw ArrayStoreException.
    

    It gets even worse if we consider generics, but that's another topic. All in all, I don't know the rationale of this design, but we need to live with it.

    0 讨论(0)
  • 2020-12-18 20:01

    Iterable<T> is the Java equivalent of IEnumerable<T>. All/most collections implement this interface (including ArrayList and arrays), so yes. But it's not an "ancestor" (which it's not in .NET either), but a common interface.

    0 讨论(0)
  • 2020-12-18 20:17

    They don't have a common ancestor, however, there are methods to cast between the two types as needed -

    • List.toArray()
    • Arrays.asList()

    So you could provide an overloaded method to cast to a common type - i.e.

    public void doAll(MyType[] array) {
        doAll(Arrays.asList(array));
    }
    
    public void doAll(List<MyType> list) {
        //... process List here.
    }
    
    0 讨论(0)
  • 2020-12-18 20:20

    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.

    0 讨论(0)
  • 2020-12-18 20:22

    Both derive from java.lang.Object. However, this isn't collection-related, which I think is what you're looking for.

    0 讨论(0)
  • 2020-12-18 20:23

    Array and List in Java do not share a common ancestor other than java.lang.Object.

    Both can be accessed using the foreach loop, like so:

    String [] array = new String [] { "foo", "bar", "baz", };
    List<String> list = Arrays.asList( "x", "y", "z");
    
    for (String s : array)
        System.out.println(s);
    
    for (String s : list)
        System.out.println(s);
    
    0 讨论(0)
提交回复
热议问题