0

I am new at Java and I am trying to sort a list called rojas who has been copied from list. When using arrays.sort and then printing it, I realized that both rojas and list are getting sorted.

public static void main(String[] args) {
    int[] list = {611, 700, 777, 901, 4124, 8000, 9014, 6213113, 15, 19, 100, 102, 150, 177, 310, 330, 400, 590, 600};

    int[] rojas = list;

    int size = 20;
    int value = 100;

    for (int i=0 ;i< size-1; i++){
        if(list[i] == value){
           System.out.println("Element found index is :"+ i);
           break;
        }
        else{
           System.out.println("Element not found");}
        
    }

    Arrays.sort(rojas);
    System.out.println("element found by binary search is in index: " + Arrays.binarySearch(rojas,100));

    System.out.println(Arrays.toString(rojas));
    System.out.println(Arrays.toString(list));
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 8
    1. What you have is not a List but an array 2. You only have 1 array object, but 2 variables `list` and `rojas` pointing at that one single array. In java objects don't get automatically cloned when you assign them to variables. If you want to make a copy of your 1 array so that you have 2 arrays [you need to create that copy yourself](https://stackoverflow.com/questions/5785745/make-copy-of-an-array) – OH GOD SPIDERS Oct 14 '22 at 14:40

4 Answers4

1

Copy the value of the array instead of the reference.

It should be

int[] rojas = Arrays.copyOf(list, list.length);
Ankit Sharma
  • 1,626
  • 1
  • 14
  • 21
0

Are you sure the list has been copied?

There is one list with two references. So sorting either variable will sort the single underlying list

Asad Awadia
  • 1,417
  • 2
  • 9
  • 15
0

As mentioned in the comments, there is only one array (not list) with two references / variables, and therefore when the array is sorted using one reference, the other variables refers the sorted array.

You should create a copy / clone the original array, which can be done like this:

int[] rojas = list.clone();

int[] rojas2 = Arrays.copyOf(list, list.length);
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

You copy the reference, not the value, as Asad Awadia mentioned.

You can do the following to create a new Array:

int[] rojas = list.clone();
Christoph S.
  • 585
  • 3
  • 16