Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

lambda

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

like image 851
Catherin Zeta Jones Avatar asked Oct 23 '25 13:10

Catherin Zeta Jones


1 Answers

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.

like image 124
tevemadar Avatar answered Oct 25 '25 03:10

tevemadar