How to fix stack overflow error in java?

I have a Movie class with a static movie Movie []. I implement Comparable and I overload the compareTo method. If similar films are the same as similar to another film, I compare them with the alphabetical order. I need to create a quicksort implementation to sort an array of movies. But in the line return this.compareTo(m);I got an error. How should I fix this?

 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;
        }
+4
source share
2 answers
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;
            }

        }

If it this.likes == m.likesreturns true, you will start an infinite recursive loop, in the end both 'this' and m will be the same in the next iteration, so there will be m values. It's your problem.

+6

if (this.likes == m.likes) {
    return this.compareTo(m);
}

compareTo , , StackOverflowError.

, Movie , . Movie, return 0.

+1

Source: https://habr.com/ru/post/1619196/


All Articles