AlldaRage
AlldaRage

Reputation: 121

Why am I getting stackoverflow?

public class SortAnimal
{
    public static Comparator<Animal> getAnimalTagComparator()
    {
        return getAnimalTagComparator();
    }

class getAnimalTagComparator implements Comparator<Animal> {

    @Override 
    public int compare(Animal o1, Animal o2) {
        return o1.getTag()-o2.getTag();         
    }
}

I have another file that generates an array and calls:

Comparator<Animal> getAnimalTagComparator = SortAnimal.getAnimalTagComparator();

Why am I getting stackoverflow on this line: return getAnimalTagComparator();

Upvotes: 0

Views: 74

Answers (2)

Eran
Eran

Reputation: 393856

getAnimalTagComparator() calls itself recursively infinite number of times (or at least until the stack overflows). That's causing a stack overflow.

You should use different names for your class and method, and change the method to something like :

public static Comparator<Animal> getAnimalTagComparator()
{
    return new AnimalTagComparator();
}

and change the class to static class AnimalTagComparator. (the static modifier is required because the AnimalTagComparator class is nested inside your SortAnimal class, and without making it static, you would need an enclosing instance of SortAnimal in order to create an isntance of AnimalTagComparator).

Upvotes: 3

Scary Wombat
Scary Wombat

Reputation: 44844

Because your code is just calling itself (you are calling a recursive method). As there is no termination of this calling, then you will eventually get a StackOverflow Error

public static Comparator<Animal> getAnimalTagComparator()
{
    return getAnimalTagComparator();  // yes this is THIS method
}

if you were wanting to call the other class you could do

public static Comparator<Animal> getAnimalTagComparator()
{
    return new getAnimalTagComparator();
}

Upvotes: 1

Related Questions