11
new String[] { "foo", "bar" }.clone();

With my favorite IDE (i.e. Eclipse), I wanted to see the source code of the above clone() method by Ctrl-clicking on it (as usual), but it brought me to the Object's native one, which provides only the signature and not the body of the method.

The autocomplete told me that the said clone() method belonged to the String class (clone() : String[] - String), but the source code of the String class doesn't provide such a method (since I'm dealing with the String[] class...).

So, where is that implementation hiding? Should the autocomplete be fixed?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sp00m
  • 47,968
  • 31
  • 142
  • 252
  • 1
    you are calling clone on an array, not on a string. – assylias Feb 12 '13 at 16:28
  • 3
    `clone` is a `native` method of `java.lang.Object`, it works on all objects. Mandatory disclosure: [clone is broken](http://www.artima.com/intv/bloch13.html). – Sergey Kalinichenko Feb 12 '13 at 16:34
  • Also please refer to the link http://stackoverflow.com/questions/6825982/how-does-clone-work-under-the-hood – user1428716 Feb 12 '13 at 16:41
  • @dasblinkenlight Note that the original question was about array-cloning, not object cloning (yes, I know arrays in Java are objects). But you can't implement a copy-constructor for an array, so... you use `[].clone()` or you use `System.arraycopy`. I see no downside to using `[].clone()`, and both Josh Bloch and Doug Lea agree that `[].clone()` is better. – Christopher Schultz Sep 16 '15 at 19:34

2 Answers2

10

The code for cloning an array is in the JVM (it is a native method). For hotspot, it is around lines 550/560 of jvm.cpp.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • Some additional information about the native `Object.clone()` method: (1) it handles both array and non-array types (slightly differently); (2) it is essentially a wrapper around `memcpy()`, (3) any references in the cloned object are copied atomically, individually, but the clone itself is not atomic. – Christopher Schultz Jan 15 '21 at 13:45
0

What is confusing is that Eclipse says that the clone method for a String array is in String class. But the length method of String array is from String[].

enter image description here

Arun Manivannan
  • 4,213
  • 3
  • 29
  • 38