2014-11-04 60 views
1

你好傢伙我是新來的網站和Java。我有一個關於鏈表的問題。我有2個班。一個叫countryNode,第二個叫countryList。 CountryNode需要2個參數,一個名爲country的變量對象和一個名爲next類型countryNode的變量。 CountryList帶有1個名爲countryNode的第一個參數,它們包含countryNode對象的鏈接列表。首先,我創建了一個方法「add()」,它將Country對象作爲參數,並將該新對象添加到列表的末尾。我做的。下面是countryList代碼:需要幫助的鏈表包含方法

public void add(Country country) { 
    CountryNode a = new CountryNode(country); 
    CountryNode current = null; 
    if(isEmpty()) 
    { 
     a.set(first); 
     first = a; 
    } 
    else{ 
     current = first; 
     while(current.getNext()!=null) 
     { 
      current = current.getNext(); 
     } 
     current.set(a); 
    } 

} 

這個問題我有麻煩的理解是這樣的:一種方法「包含了」,需要一個國家對象作爲參數,並檢查該國的名稱可以在列表中找到。要檢查Country的對象foo是否等於Country的對象欄,則必須覆蓋Country Country中的「equals方法」。我無法理解這個問題並執行它。請隨身攜帶我過去3天一直忙碌(工作,學校你的名字)這麼累,幾乎沒有任何睡眠。

以下是我爲country,countryNode寫的代碼。

public class Country { 

private String countryNames; 
private SubscriptionYear[] subscriptions; 
private int size; 
private int location; 

public Country(String country, int arraylength) 
{ 
    this.countryNames = country; 
    this.size = arraylength; 
    subscriptions = new SubscriptionYear[size]; 
    location = 0; 
} 

public void addSubscriptionYear(int year, double subscription) 
{ 
     subscriptions[location]= new SubscriptionYear(year, subscription); 
     ++location; 
} 

public double getNumSubscriptionsForPeriod(int start, int end) 
{ 
    double sum = 0; 

    int head = start-subscriptions[0].getYear(); 
    int tail = head+(end-start); 

    if(head>=0&&tail<subscriptions[subscriptions.length-1].getYear()) 
    { 
    for(int k=head;k<=tail;k++) 
    { 
     sum += subscriptions[k].getSubscription(); 
    } 
    }else{ sum = -1;} 
    return sum; 
    } 

public String toString() 
{ 
    System.out.print(countryNames+"\t"); 
    for(SubscriptionYear s: subscriptions) 
    { 
     //System.out.print(countryNames+"\t"); 
     System.out.print(s.getSubscription()+"\t"); 
    } 
    System.out.println(); 
    return ""; 
} 
} 

我的代碼countryNode:

public class CountryNode { 
private Country country; 
private CountryNode next; 

public CountryNode(Country country) 
{ 
    this.country = country; 
    this.next = null; 
} 
public CountryNode(Country country, CountryNode n) 
{ 
this.country = country; 
this.next = n; 
} 

public void set(CountryNode x) 
{ 
this.next = x; 
} 
public CountryNode getNext() 
{ 
return this.next; 
} 
public Country getCountry() 
{ 
return country; 
} 

} 
+1

雖然我很同情,但現在還沒有要求我們爲您編寫代碼。特別是作業代碼...因爲這似乎是。睡覺。去睡一會。明天寫出'contains'方法的代碼,如果你仍然有問題...向我們展示你寫它的嘗試。 – 2014-11-04 11:54:49

回答

0

的equals()方法Java提供的方法總是檢查引用的平等,如果進行比較指向同一參考兩個對象將返回的結果爲兩個。考慮到你的代碼,如果你創建兩個像下面這樣的Country對象並比較它們,結果將是錯誤的,因爲它們沒有指向同一個引用。

Country c1=new Country("abc", 10); 
Country c2=new Country("abc", 10); 

這就是爲什麼我們重寫equals方法來比較對象的內容而不是引用。不知道這是否完全回答你的問題,因爲我沒有得到整個問題。