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.

1
  • 1
    stackoverflow.com/questions/5554734/… - 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. Commented Jun 15, 2020 at 22:44

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

-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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.