Search code examples
javastack-overflowcomparatorcomparable

How to fix a stack overflow Error in java?


I have a class Movie with a static array Movie[] movies. I implement the Comparable and i overload the method compareTo. If the likes of a movie are same with the likes of another movie then i compare them with alphabetical order. I have to create a quicksort implementation to sort an array of movies. But in line return this.compareTo(m); i got a stack overflow Error. How i am supposed to 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;
        }

Solution

  • 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 this.likes == m.likes returns true, you'll start an infinite recursive loop, after all, both the 'this' and 'm' are the same in the next iteration(s), so will their values of m be. That's your problem.