4

I'm implementing class

class PairStringList extends ArrayList<String> {
...

@Override
    public <T> T[] toArray(T[] a) {
        return super.toArray(a);
    }
}

I have tests written for this class, and they use such a declaration:

assertArrayEquals(new String[]{}, list.toArray(String[]::new));

I see that they use Lambda as parameter. How can I implement toArray() method to run the test correctly? Now I have the next Build Output:

no suitable method found for toArray(String[]::new) method Java.util.Collection.toArray(T[]) is not applicable (cannot infer type-variable(s) T (argument mismatch; Array is not a functional interface))

Any ideas, how can I solve the problem?

Note: I can't change the code of tests

Thanks to everyone! Issue was solved. The problem was that test were written in Java 11, but I was using Java 8. After update to Java 11 everything builds and compiles

2
  • Your test compiles and passes for me. What type is your variable list in the test? Commented May 24, 2021 at 7:47
  • Can you try if an empty class, class PairStringList extends ArrayList<String> {} passes that test already? Commented May 24, 2021 at 10:48

1 Answer 1

2

That's a different toArray() method, you can piggyback it too by calling super:

@Override
public <T> T[] toArray(IntFunction<T[]> generator) {
  return super.toArray(generator);
}

or even "steal" the default implementation from /lib/src.zip/java.base/util/Collection.java:

@Override
public <T> T[] toArray(IntFunction<T[]> generator) {
  return toArray(generator.apply(0));
}   

and in fact your test may pass even without implementing anything, as the ArrayList<String> superclass provides them anyway.

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

4 Comments

@Override shall be not be required there.
@Naman @Override is not something that's required ever. It indicates that you wanted to override an existing method, so the compiler can tell you when it does not happen, because the inheritance chain is different what the programmer thought, or even just some typo happened. Here indeed existing methods are overridden, the entire thing would work with an empty class body. I'm not sure what OP is really expected to do, but probably not these attempts (calling super without doing anything)
I meant unless one is on Java-11, the toArray(IntFunction<T[]> generator) is not overridden and the code-shared by you wouldn't compile.
@Naman ah, ok, now I understand your concern. I can't really know what version they are using, but Java 8 is the only one which is alive and wouldn't ovverride an existing method here.

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.