6

Im working with the following method:

public void m(List<? extends Object[]> objs){
    objs.stream()
        .map(oa -> oa[0])   //compile error
                            //array type expected
        .forEach(System.out::println); 

}

DEMO

Why doesn't it work? I thought everything that extends array can be viewed as an array. Actually I can get length from the array.

3
  • 1
    Downvoter, would you be so kind and explain in comments why doesn't it work? Why do I need to cast explicitly to Object[]? Commented May 11, 2017 at 17:38
  • 3
    If you change m(List<? extends Object[]> objs) to m(List<Object[]> objs) it compiles, but I'm not answering because I don't understand the implications of this change or what's wrong with your original. Commented May 11, 2017 at 17:45
  • @StephenP Unfotunately I cannot change the signature. Commented May 11, 2017 at 17:48

1 Answer 1

5

There is actually no such class that extends Object[]; each array has a fixed type and its own class, eg MyClass[].class

You should use a typed method:

public <T> void m(List<T[]> objs){
    objs.stream()
            .map(oa -> oa[0])   // no compile error
            .forEach(System.out::println);

}
Sign up to request clarification or add additional context in comments.

4 Comments

Never thought abt it, but indeed class MyClass extends Object[]{ } does not compile.
@St.Antario arrays are a native impl - you can't do anything with them
@Bohemian nit it's not an implementation reason that precludes it, the forbidden by specification. (Failing to find the relevant section of JLS on my phone...)
@AndyTurner: I would say it follows from JLS8 - 10.8: "Although an array type is not a class, the Class object of every array acts as if: * The direct superclass of every array type is Object."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.