1

Can I copy an array to itself without creating a new array object (purpose of increase it size)? I know that with using Collections I will have no such problems, so you don't need to remind me about Collections usage to solve this problem. I was sure that Arrays.copyOf and System.arraycopy creates a new objects for this purpose and leave old array object in heap.
But today I was googling and found that question at stack How to effectively copy an array in java? there written that System.arraycopy doesn't create new object when copies an array, it copies into existing array. I was wonder, when I read this and suggest that this will work for copyring array into itself but I've not found appropriative example to do this. So there are a way to copy an array to itself with increasing it size without creating new array object(that heap will hold) or not?

Community
  • 1
  • 1
Mike Herasimov
  • 1,319
  • 3
  • 14
  • 31

2 Answers2

3

System.arraycopy can be used to copy an array to iteself.

From the Javadoc :

 * If the <code>src</code> and <code>dest</code> arguments refer to the
 * same array object, then the copying is performed as if the
 * components at positions <code>srcPos</code> through
 * <code>srcPos+length-1</code> were first copied to a temporary
 * array with <code>length</code> components and then the contents of
 * the temporary array were copied into positions
 * <code>destPos</code> through <code>destPos+length-1</code> of the
 * destination array.

However, copying an array to itself wouldn't help you increase its size, since you can't increase the size of an array. You must create a new, larger, array and copy the elements of the original array to the new array.

Community
  • 1
  • 1
Eran
  • 387,369
  • 54
  • 702
  • 768
2

Can I copy an array to itself without creating a new array object (purpose of increase it size)?

Yes, you can copy an array to itself.

No, you can't increase (or decrease) the size of an array. Copying an array to itself won't achieve that.

The size of an array cannot be changed. If you need the array to be larger or smaller than it currently is, you need to create a new array, and copy from the old to the new as appropriate.

I was sure that Arrays.copyOf and System.arraycopy creates a new objects for this purpose and leave old array object in heap.

Arrays.copyOf creates a new array.

System.arraycopy doesn't create a new array ... but it doesn't change the size of any existing array either.

So there are a way to copy an array to itself with increasing it size without creating new array object(that heap will hold) or not?

There isn't.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216