0

How to pass integer arrays in Android from one activity to a fragment by value? Whenever I pass an array using Bundle or Intent to pass to another activity, it seems that it is passed by reference.

I am passing an array from a fragment to an activity where I pass it to 2 functions which sorts the array using 2 different algorithms. However, the 2nd sorting algorithm gets a sorted array because the 1st algorithm has already sorted it before. I need that both function calls have the same input array.

int[] inputArray = getIntent().getIntArrayExtra("input")    
bubbleSort(inputArray);     
mergeSort(inputArray);

Even if I make a copy of the array it doesn't work because probably the array was passed by reference.

clemens
  • 16,716
  • 11
  • 50
  • 65
  • 1
    Java is always pass by value... You need to clone the array to get an independent reference – OneCricketeer Nov 28 '17 at 04:37
  • 1
    Also, `int[] otherArray = inputArray`is not a copy. That's two references to the same array – OneCricketeer Nov 28 '17 at 04:40
  • you can pass the int array by this int[] inputArray = {1,0}; bundle.putIntArray("",inputArray); – Hemant Parmar Nov 28 '17 at 04:40
  • @cricket_007 I agree about the copy. But when I pass it to my sort class constructor it sorts the same array instead of sorting the local array. – Pranit Kulkarni Nov 28 '17 at 19:53
  • There is no "different array" here so I don't know what you mean. The array you get within the method is the same one as outside the method. The second sort method will get the bubble sorted one unless you clone it – OneCricketeer Nov 28 '17 at 20:03

0 Answers0