I want to pass an array to a method but I know arrays are passes by reference, so the original array gets modified. A work around that I found is to create a copy of the array inside the method and then modify the copy, but what is the best way to pass the copy of an array or it will be better to create a copy inside the method. here’s my code
take a look at reverse method in ArrayUtils class
package com.javablackbelt.utils;
import java.util.ArrayList;
import java.util.Arrays;
public class ListUtils {
public static void main(String arg[]) {
String[] arr = {"one", "two", "three", "four", "five"};
ArrayUtils.print(arr);
System.out.println();
String [] reversedArr = ArrayUtils.reverse(arr);
ArrayUtils.print(reversedArr);
System.out.println();
ArrayList<String> list = ArrayUtils.toArrayList(arr);
ListUtils.print(list);
}
public static void print(ArrayList<String> aStr) {
System.out.print("list: [ ");
for(String l: aStr)
System.out.print(l+" ");
System.out.println(" ] size: "+aStr.size());
}
}
package com.javablackbelt.utils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class ArrayUtils {
public static void print(String[] arr) {
System.out.print("Array: [ ");
for(String str: arr) {
if(str != null)
System.out.print(str.toString()+" ");
}
System.out.print(" ] size: "+arr.length);
}
public static String[] reverse(String[] arr) {
String[] a = arr;
List<String> list = Arrays.asList(a);
Collections.reverse(list);
String[] newArr = (String[]) list.toArray();
return newArr;
}
public static ArrayList<String> toArrayList(String[] arr) {
ArrayList<String> arrList = new ArrayList<String>();
for(int i = arr.length-1; i >= 0; i--)
arrList.add(arr[i]);
return arrList;
}
}
You can create a copy of the array and hence be saved from editing the original array,