14

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Hannesh
  • 7,256
  • 7
  • 46
  • 80
  • 4
    Good question because `T` can't be `int` type. – Peter Lawrey Sep 17 '12 at 10:44
  • Sounds like a compiler/IDE problem, because there's really just one valid overload that could be used (the first one). Plus: Eclipse can easily compile this line and knows exactly which one to call. – Joachim Sauer Sep 17 '12 at 10:49
  • It must be a compiler problem if it works in eclipse then. Still, anyone know if there a way to coax the compiler into picking one? – Hannesh Sep 17 '12 at 10:55
  • Just wondering - why aren't you using an `ArrayList` as that would handle the resizing for you. – David Webb Sep 17 '12 at 11:08
  • Have you tried casting the first argument to int[]: `Arrays.copyOf((int[]) elements, elements.length * 2)`? – JB Nizet Sep 17 '12 at 11:12
  • @Dave, because ArrayList boxes each value, which has a pretty big overhead. – Hannesh Sep 17 '12 at 11:21
  • @JB Nizet, I've tried, but that didn't work either – Hannesh Sep 17 '12 at 11:21
  • Sounds like a bug for me. I just tried this IDE, static imports seems not to work either. And there not hint about which compiler is used. Iwould suggest to raise a bug or switch to another android IDE – cporte Sep 17 '12 at 12:32

1 Answers1

1

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.

gexicide
  • 38,535
  • 21
  • 92
  • 152