我有一个带有静态数组Movie []电影的类电影.我实现了Comparable,我重载了方法compareTo.如果电影的喜欢与另一部电影的喜欢相同,那么我将它们与字母顺序进行比较.我必须创建一个快速排序实现来排序电影数组.但在排队中return this.compareTo(m);
我得到了堆栈溢出错误.我应该如何解决这个问题?
public int compareTo(Movie m) { if (this.likes == m.likes) { //DefaultComparator cmp = new DefaultComparator(); return this.compareTo(m); } else if (this.likes > m.likes) { return 1; } else { return -1; } } public static Movie[] sort(Movie[] m) { if (m == null || m.length == 0) { return null; } else { movies = m; quicksort(0, movies.length - 1); // sort the entire array return movies; } } public static void quicksort(int left, int right) { int i = left; int j = right; Movie pivot = movies[left + (right - left) / 2]; while (i <= j) { while (movies[i].compareTo(pivot) == -1) { i++; } while (movies[j].compareTo(pivot) == 1) { j--; } if (i <= j) { exch(i, j); i++; j--; } } if (left < j) { quicksort(left, j); } if (i < right) { quicksort(i, right); } } public static void exch(int i, int j) { Movie temp = movies[i]; movies[i] = movies[j]; movies[j] = temp; }
Stultuske.. 6
public int compareTo(Movie m) { if (this.likes == m.likes) { //DefaultComparator cmp = new DefaultComparator(); return this.compareTo(m); } else if (this.likes > m.likes) { return 1; } else { return -1; } }
如果this.likes == m.likes
返回true,你将启动一个无限递归循环,毕竟,'this'和'm'在下一次迭代中都是相同的,因此m的值也是如此.那是你的问题.
public int compareTo(Movie m) { if (this.likes == m.likes) { //DefaultComparator cmp = new DefaultComparator(); return this.compareTo(m); } else if (this.likes > m.likes) { return 1; } else { return -1; } }
如果this.likes == m.likes
返回true,你将启动一个无限递归循环,毕竟,'this'和'm'在下一次迭代中都是相同的,因此m的值也是如此.那是你的问题.