简体   繁体   中英

How to implement toArray() method for ArrayList with Lambda parameter?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM