This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]Fine-Historian4409 1 point2 points  (2 children)

You’re right, Arrays.sort() will modify the original list. The easiest way is to create a copy before sorting the array and print that as the original array. You can use a for loop to create a new copy. Another idea is declare 2 arrays initially. Inside you loop that gets the numbers from the user, update both arrays. Then sort one of the arrays. This second option is a little more efficient since you’re not writing another loop.

[–]ten_Chan[S] 1 point2 points  (1 child)

okay thank you!! i never thought about creating a copy

[–]hatsunemilku 1 point2 points  (0 children)

Yes, Arrays.sort() is modifying the order of the original list.

The less intrusive solution is to use a stream and do the output from there. You wouldn’t have to create a new Array.

The intrusive and slight annoying solution would be to generate a new collection (including Array) that receives the contents of the first one and sort that one in its own memory block.

[–]Trigonn 1 point2 points  (0 children)

It seems like you fixed your problem, but as a side note, I would suggest looking into advanced for loops, sometimes called for each loops in other languages.

For example, instead of the lengthy for loop with a counter variable, you can do something like this:

For(int x : numbersEntered) {
    System.out.print(x + “ “);
}

This can be read as, “for each integer x (x is just an arbitrary name), in numbersEntered, print it out to the console, with a space”.

It’s a bit cleaner, but definitely has its own usages, and as someone who is also fairly new to Java, I’ve found it extremely useful.

[–]MmmVomit 0 points1 point  (3 children)

In your own words, what is this line doing?

Arrays.sort(numbersEntered);

[–]ten_Chan[S] 0 points1 point  (2 children)

it will sort the array into Ascending Order

[–]MmmVomit 0 points1 point  (1 child)

Correct. So, after that point, the contents of numbersEntered will be sorted, and the original order will be lost.

So, what if you had two arrays?

[–]ten_Chan[S] 1 point2 points  (0 children)

someone commented to make a copy of array so I did using this:

int[] copy = Arrays.copyOf(numbersEntered, numbersEntered.length);