0

I am learning Java and coding up the QuickSort class. At some point one needs to swap elements in the array, so I am trying to do that with the Collections.swap, which is recommended, for instance, in this question. However, javac QuickSort.java throws an error at me:

error: swap(Object[],int,int) has private access in Collections

What am I doing wrong here? Complete code of QuickSort.java:

package src.sort;

import java.util.Collections;

public class QuickSort {
    public static void sort(Comparable[] xs) {
        sort(xs, 0, xs.length);
    }

    private static boolean less(Comparable x, Comparable y) {
        return x.compareTo(y) < 0;
    }

    private static void sort(Comparable[] xs, int fst, int lst) {
        if (fst >= lst) return;

        int i = fst, j = lst;

        Comparable pivot = xs[(i + j) / 2];

        while (i <= j) {
            while (less(xs[i++], pivot));
            while (less(pivot, xs[j--]));

            if (i <= j) Collections.swap(xs, i++, j--);
        }

        sort(xs, fst, j);
        sort(xs, i, lst);
    }
}
Community
  • 1
  • 1
alisianoi
  • 2,003
  • 3
  • 31
  • 46

1 Answers1

3

The error is quite explicit. You can't call that method, since it's a private method, accessible only be code within the Collections class. It's easy enough to write your own method that would have the same functionality as this simple method.

The swap method recommended in the linked question is a public method that swaps two elements of a List - public static void swap(List<?> list, int i, int j). The method you tried to call is a different method, that swaps two elements of an array, and it's private - private static void swap(Object[] arr, int i, int j).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • How come then it is used in [the question I linked](http://stackoverflow.com/questions/15963549/arraylist-swap-elements?lq=1)? – alisianoi Mar 07 '16 at 12:01
  • 4
    @all3fox `swap(List> list, int i, int j);` is public while `swap(Object[] arr, int i, int j)` is private. – Eran Mar 07 '16 at 12:02