Java 9 Array how to copy and clone

Coping and clone of Array in Java may seem easy and trivial but is a tricky one for new programmers to Java. Sometimes can be mistaken by referencing to the same Array instead of copying.

In this post Java 9 array:

  • copy
  • clone
  • reference
  • copy first N elements
  • copy last N elements

Java Array Clone vs Reference

In order to get a fresh copy of array in java you need to use method: clone(). In this example you will see clone vs reference in java:

int[] years = {2015, 2016, 2017, 2018};
int[] yearsNew = years.clone();    // clone the array into a new one
int[] yearsRef = years;            // do a reference to the same array
years[0] = 0;
System.out.println("years: " + Arrays.toString(years));         //[0, 2016, 2017, 2018]
System.out.println("yearsNew: " + Arrays.toString(yearsNew));      //[2015, 2016, 2017, 2018]
System.out.println("yearsRef: " + Arrays.toString(yearsRef));      //[0, 2016, 2017, 2018]

result:

years: [0, 2016, 2017, 2018]
yearsNew: [2015, 2016, 2017, 2018]
yearsRef: [0, 2016, 2017, 2018]

Otherwise as you see you are referencing to the old array.

Java Array copy all vs copy first elements

You can use another method:

Arrays.copyOf

in order to get copy of array. If you want to get first N elements than you can pass parameter as shown:

String[] years2 = {"2015", "2016", "2017", "2018", "2019"};
String[] yearsAll = Arrays.copyOf(years2, years2.length);
String[] yearsCopy2 = Arrays.copyOf(years2, 2); 
System.out.println("years2: " + Arrays.toString(years2));
System.out.println("yearsAll: " + Arrays.toString(yearsAll));
System.out.println("yearsCopy2: " + Arrays.toString(yearsCopy2));

result:

years2: [2015, 2016, 2017, 2018, 2019]
yearsAll: [2015, 2016, 2017, 2018, 2019]
yearsCopy2: [2015, 2016]

Java Array copy all vs copy last elements

Another way to copy arrays is by method:

Arrays.copyOfRange

as you can see in this example than you can copy all elements or the last N elements:

String[] years3 = {"2015", "2016", "2017", "2018", "2019"};
String[] yearsFull = Arrays.copyOfRange(years2, 0, years2.length); 
String[] yearsLast3 = Arrays.copyOfRange(years2, years2.length-3, years2.length); 
System.out.println("years3: " + Arrays.toString(years3));
System.out.println("yearsFull: " + Arrays.toString(yearsFull));
System.out.println("yearsLast3: " + Arrays.toString(yearsLast3));

result:

years3: [2015, 2016, 2017, 2018, 2019]
yearsFull: [2015, 2016, 2017, 2018, 2019]
yearsLast3: [2017, 2018, 2019]

Related Article