2014-11-04 28 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方法来比较对象的内容而不是引用。不知道这是否完全回答你的问题,因为我没有得到整个问题。