-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;
5
  • where are you trying to store this array? Commented Aug 28, 2020 at 0:09
  • are you trying to clone the exact values? Commented Aug 28, 2020 at 0:12
  • 1
    int[] sortedArray = array.clone(); Arrays.sort(sortedArray); Commented Aug 28, 2020 at 0:13
  • you declare on return type double Commented Aug 28, 2020 at 0:14
  • 1
    stackoverflow.com/questions/14149733/… This answer explains the use of the clone() method Commented Aug 28, 2020 at 0:21

1 Answer 1

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

2 Comments

you could use return immediately without creating int[] newArr reference :)
yes, but he said he wanted to keep track of both array's so i just did that for clarity

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.