0

I'm trying to copy a sub-array from my initial array into another second array using System.arraycopy

public class Main {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] fruits = {"orange","pomme","poire","melon","fraise"};
    String[] redFruits = {};

    System.arraycopy(fruits, 0, redFruits, 0, 2);


    for(String fruit : fruits) {
        System.out.println(fruit);
    }

    System.out.println("/**************************/");

    for(String fruit : redFruits) {
        System.out.println(fruit);
    }

 }

}

NB: this is not a duplicated question, I checked out all the relative questions no gave me an answer.

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • 1
    https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it/ - 25 answers here should help you with the concept of `ArrayIndexOutOfBounds` and how to debug it so that you never get stuck on it ever again. – Harshal Parekh Jun 15 '20 at 22:44

2 Answers2

1

You need to allocate space in the second array before copying elements into it:

String[] fruits = {"orange","pomme","poire","melon","fraise"};
String[] redFruits = new String[2];
System.arraycopy(fruits, 0, redFruits, 0, 2);

System.out.println(Arrays.toString(fruits));
System.out.println(Arrays.toString(redFruits));

Output:

[orange, pomme, poire, melon, fraise]
[orange, pomme]
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
-1

Just one info. Array is fixed size container. It is not elastic, and it cannot be resized after creation.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Lonestar
  • 51
  • 6