需要有关链接列表的帮助包含方法

时间:2014-11-04 11:38:34

标签: java linked-list

我对链表有疑问。我有2节课。一个名为countryNode,第二个名为countryList。 CountryNode有2个参数,一个名为country的变量对象和一个名为countryNode的next的变量。 CountryList采用一个名为countryNode的名为first的参数,该参数包含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对象作为参数,并检查是否可以在列表中找到该国家/地区的名称。要检查Country类型的对象foo是否等于Country类型的对象栏,您必须覆盖类Country中的“equals方法”。我无法理解这个问题并实施它。

下面是我为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 个答案:

答案 0 :(得分:0)

Java提供的equals()方法总是检查引用是否相等,如果被比较的两个对象指向同一个引用,则返回结果为2。考虑到您的代码,如果您创建两个Country对象(如下所示)并进行比较,则结果将为false,因为它们未指向相同的引用。

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

这就是为什么我们重写equals方法来比较对象的内容而不是引用。不确定这是否完全回答了你的问题因为我没有得到完整的问题。

相关问题