-3

I am trying to store a sorted array separate from the original array. I need to be able to access both arrays without altering the original in anyway. I have tried to understand how to to .clone but I can't seem to understand what I am doing wrong. I have my code below, I am passing an array from above into this method and want to sort and store it. Am I even close to being correct here?

public static double sortArray(int[] array) {
        //Sort the array
        Object tempObj = array.clone();
        Arrays.sort(tempObj);
        sortedArray[] = tempObj;

1 Answers1

0

You can do this with the new sorted array, using java 8 streams:

int[] newArr = Arrays.stream(array).sorted().toArray(int[]::new);

Then change your method return type to int[]:

public static int[] sortArray(int[] array) 
{
    int[] newArr = Arrays.stream(array).sorted().toArray(int[]::new); 
    return newArr; 
}
beastlyCoder
  • 2,349
  • 4
  • 25
  • 52