Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear up this ambiguous call to Arrays.copyof()?

I'm running AIDE on my Android phone, and am having trouble compiling the following bit of Java code:

elements = Arrays.copyOf(elements, elements.length * 2);

Here elements is of type int[]. The error I'm getting from AIDE is

Several methods are applicable to (int[], int): 'java.util.Arrays.copyOf(int[], int)' and 'java.util.Arrays.copyOf<T>(T[], int)'

I would've expected the compiler to pick the former option, but it doesn't. How can I resolve this?

like image 620
Hannesh Avatar asked Sep 17 '12 10:09

Hannesh


1 Answers

This is a compiler/IDE problem. However, Arrays.copyOf is a quite trivial function, so simply write your own version of it if the problem can't be fixed with IDE/compiler updates. Another way would be to use reflection to call it. But it comes with some runtime overhead and also makes the code look awkward, so I suggest implementing your own version.

Here is the code:

public static int[] copyOf(int[] original, int newLength) {
    int[] copy = new int[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

Of course, if you then get the same problem for System.arraycopy, then this does not work. Simply try it. If it does not work, you can place it in a helper class and use a non-buggy compiler to compile this helper class.

like image 117
gexicide Avatar answered Nov 13 '22 12:11

gexicide