2016-10-26 49 views
-6
public Dog[] dogList = 
    { 
     new Dog(1, 2, "Bacon"), 
     new Dog(3, 4, "Cheese"), 
     new Dog(8, 6, "Steak"), 
     new Dog(5, 6, "Lamb"), 
     new Dog(12, 14, "Caviar") 
    }; 

每當我運行我的程序我有一個StackOverflowError。我該如何解決這個堆棧溢出錯誤?

System.out.println(new Dog(2, 3, "hi").compareTo(new Dog(1, 2, "a"))); 

我通過該代碼運行它。 狗類的源代碼:

package Luka; 

import java.util.Arrays; 

public class Dog extends Animal implements Comparable<Dog>{ 



    public void eat(String food) 
    { 
     System.out.println("The dog enjoyed his meal of " + food); 
    } 
    public int compareTo(Dog other) 
    { 
     if(this.age < other.age) 
     { 
      int returnNum = -1; 
      return returnNum; 
     } 
     else if(this.age > other.age) 
     { 
      int returnNum = 1; 
      return returnNum; 
     } 
     else 
     { 
      int returnNum = 0; 
      return returnNum; 
     } 
    } 
    public String toString(int weight,int age,String foodType) 
    { 
     return "The dog weighs "+weight+", is "+age+" years old, and eats "+foodType+" for dinner."; 
    } 
    public Dog(int weight, int age, String foodType) 
    { 
     this.weight = weight; 
     this.age = age; 
     this.foodType = foodType; 
    } 
     public Dog[] dogList = 
     { 
      new Dog(1, 2, "Bacon"), 
      new Dog(3, 4, "Cheese"), 
      new Dog(8, 6, "Steak"), 
      new Dog(5, 6, "Lamb"), 
      new Dog(12, 14, "Caviar") 
     }; 
} 
+3

請提供'Dog' class'源代碼。 –

+2

到目前爲止您發佈的代碼沒有解釋該異常。很可能,您的構造函數或compareTo()調用會執行一些遞歸(它不應該這樣做)。 – GhostCat

回答

1

只要你有一個變量初始化,初始化變量的代碼是有效前置到你的構造(S)。

例如:

public Dog[] dogList = { new Dog(1, 2, "Bacon"), ... }; 

public Dog(int weight, int age, String foodType) { 
    this.weight = weight; 
    this.age = age; 
    this.foodType = foodType; 
} 

等同於:

public Dog[] dogList; 

public Dog(int weight, int age, String foodType) { 
    this.dogList = { new Dog(1, 2, "Bacon"), ... }; 

    this.weight = weight; 
    this.age = age; 
    this.foodType = foodType; 
} 

所以你無條件調用Dog構造函數中Dog構造。

Dog類中刪除dogList,或使其成爲static