2
public void swap(int a, int b) {                                                                                                                                                                                          
    int indexA = Arrays.asList(nums).indexOf(a);
    int indexB = Arrays.asList(nums).indexOf(b);

    nums[indexA] = b;
    nums[indexB] = a;
}
public void selectionSort() {
    int x = 0;
    findIndexOfMinAfter(0);
    swap(nums[x], nums[x + 1]);
}

int[] nums is an array I passed in. When I called the swap method, both a and b exist in the array but indexA and indexB return -1. Any idea why it does that?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
laura815
  • 33
  • 2

1 Answers1

1

Arrays.asList is a generic method that takes an array of objects. In this case, the entire int array is considered as an object because its elements are of the primitive type int. As a result, Arrays.asList is returning a list of arrays instead of a list of integers.

You can solve this by turning nums into an array of Integers:

Integer[] nums;  // instead of int[]
M A
  • 71,713
  • 13
  • 134
  • 174