-5

I'm reading Java complete reference book, there I encountered following code example, I was expecting the output to be AAAAAAAAAA (10 Times) but I got the array right rotated by one.

In this thread devs are saying that

The difference is that Arrays.copyOf does not only copy elements, it also creates a new array. System.arraycopy copies into an existing array.

but the output saying something else.

public class TestClass {
    public static void main(String[] args) {
        byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
        System.arraycopy(a, 0, a, 1, a.length - 1);
        System.out.println(new String(a));
    }
}

why i'm expecting AAAAAAAAAA

pick A at 0, put A at 1 -> AACDEFGHIJ

pick A at 1, put A at 2 -> AAADEFGHIJ

....

......

PS: turns out System.arraycopy can be used to efficiently rotate(shift) an array of any type.

Rajat
  • 2,467
  • 2
  • 29
  • 38
  • See also https://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa – Raedwald Jan 13 '20 at 09:35
  • 1
    Does this answer your question? [What is more efficient: System.arraycopy or Arrays.copyOf?](https://stackoverflow.com/questions/2589741/what-is-more-efficient-system-arraycopy-or-arrays-copyof) – Vishwa Ratna Jan 13 '20 at 09:35

1 Answers1

2

That invocation of System.arraycopy is simply copying the portion of the array between the element 0 and the penultimate element into the array, starting at the element 1.

System.arraycopy(a, 0, a, 1, a.length - 1);
              // ^                          Copy a portion of array a
              //    ^                       starting at position zero
              //             ^              for this many elements.
              //       ^                    into array a
              //          ^                 starting writing at position 1

So it's overwriting

[65, 66, 67, 68, 69, 70, 71, 72, 73, 74]

with

     65, 66, 67, 68, 69, 70, 71, 72, 73

and you end up with

[65, 65, 66, 67, 68, 69, 70, 71, 72, 73]

If you did this again, you'd have

[65, 65, 65, 66, 67, 68, 69, 70, 71, 72]

and again

[65, 65, 65, 65, 66, 67, 68, 69, 70, 71]

...but you have to keep on doing it if you want the whole array to be 65 (and you may as well just fill the array instead).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • yeah that's the desired result, since I first visited the mentioned thread there they mentioned in place copy without creating the intermediate array, thanks for the abstraction. – Rajat Jan 13 '20 at 10:29