如何比较通用LinkedList中的对象

时间:2014-11-16 01:06:27

标签: java generics singly-linked-list

如何比较通用链接列表中的对象?我从头开始编写链表。我有一个名为Country的类,它从csv文件中读取并存储国家名称及其特定年份的蜂窝统计数据。它读取从1960年到2012年的数据。我的程序运行正常,因为我能够打印出列表。但是当我搜索列表以匹配在控制台中打印出的国家/地区名称时。它说没有找到。我是泛型的新手,我觉得有些不对劲,因为我试图在类Country中覆盖equals方法来比较名称。但我没有调用类Country中的equals方法。我尝试调试equals方法,看看是否曾经通过放置print out语句来调用它,但它从未调用过。我的猜测是因为使用了泛型。我需要一些帮助才能解决这个问题。这是我对应用程序的一个问题,因为我的contains方法根本没有比较国家名称。

班级链表

public class LinkedList<T> {

private Node<T> first;

public LinkedList()
{
    this.first = null;
}

//returns true if list is empty
public boolean isEmpty()
{
    return (first==null);
}
//adds the node to the end of the list
public void add(T obj)
{
    Node<T> newNode = new Node<T>(obj);
    if(this.isEmpty())
    {
        newNode.setNode(first);
        first = newNode;
    }
    else
    {
        Node<T> current = first;
        while(current.getNext()!=null)
        {
            current = current.getNext();
        }
        current.setNode(newNode);
    }
}

public String toString()
{
    String result ="";
    if(this.isEmpty())
    {
        result += "Cannot print an empty list";
        return result;
    }
    else
    {
        Node<T> current = first;
        while(current!=null)
        {
            result +=current.getObj();
            current = current.getNext();
        }
        return result;
    }
}
//searches for the countryName and returns the country if found
public T contains(T obj)
{
    if(this.isEmpty())
    {
        return null;
    }
    else
    {
        Node<T> current = first;
        while(current!=null)
        {
            if(current.getObj().equals(obj))
            {
                return current.getObj();
            }
            current= current.getNext();
        }
        return null;
    }
}
}

类节点:

public class Node<T> {

private T data;
private Node<T> next;

public Node(T data)
{
    this.data = data;
    this.next = null;
}

public Node(T data, Node<T> next)
{
    this.data = data;
    this.next = next;
}

public void setNode(Node<T> next)
{
    this.next = next;
}

public Node<T> getNext()
{
    return this.next;
}

public T getObj()
{
    return data;
}

  }

class Country:覆盖方法等于

public class Country  {

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

public Country(String country)
{
    this.countryNames = country;
}
public Country(String country, int arraylength)
{
    this.countryNames = country;
    this.size = arraylength;
    subscriptions = new SubscriptionYear[size];
    location = 0;
}
//adds the subscription.
public void addSubscriptionYear(int year, double subscription)
{
        subscriptions[location]= new SubscriptionYear(year, subscription);
        ++location;
}

//overrides the toString method and prints out the countries.
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  "";
}
//returns countryName
 public String getName()
 {
    return this.countryNames;
 }
//overrides the equals method and returns country name if found
public boolean equals(Country obj)
{
    System.out.println("In the equals method");
    return this.countryNames.equalsIgnoreCase(obj.countryNames);
}

}

main中的

方法,调用函数来比较节点中国家的名称。

private void testRandomListOfCountries(Country [] allCountries)
{   
    Scanner keyboard = new Scanner(System.in);
    System.out.println("How many countries do you want to add to the list?");
    int requestedSize = Integer.parseInt(keyboard.nextLine());


    // Build the list out of a random selection of countries.
    Random random = new Random();
    LinkedList<Country> selectedCountries = new LinkedList<Country>();
    for (int i = 0; i < requestedSize; i++)
    {
        int selectedIndex = random.nextInt(allCountries.length);
        selectedCountries.add(allCountries[selectedIndex]);
    }


    // Note: To debug your list, comment this line in
    System.out.println("List of countries: " + selectedCountries);


    // Check if the name of a country is in the list.
    // If the country is found, print the details.
    // Otherwise output not found.
    System.out.println("\nWhat country do you want to search for?");
    String countryToFind = keyboard.nextLine();
    //Country obj = new Country(countryToFind);
    Country foundCountry = selectedCountries.contains(new Country(countryToFind));
    if (foundCountry != null)
    {
        System.out.println("Country " + countryToFind + " found with details:\n" + foundCountry);
    }
    else
        System.out.println("Country " + countryToFind + " not found.");

}

下面的输出代码:伯利兹打印在屏幕上,我输入伯利兹和 它说即使伯利兹列入名单也没有找到

How many countries do you want to add to the list?
4
 European Union 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.010455902 0.014641232 0.022017047 0.033736759 0.059970029 0.099394983 0.172494402 0.290883796 0.468609861 0.647271896 0.88803523  1.180245548 1.773778201 2.896911981 4.555055819 7.189007007 11.51481484 19.70441779 33.91179565 53.57287113 64.80565912 70.93170081 77.89306636 85.94063784 95.79155903 105.012288  115.1562612 120.8409684 121.1416294 119.2250553 121.9304985 123.7159497 
 Sint Maarten (Dutch part)  0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
 Belize 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.201592581 0.411172831 0.747480214 1.028369629 1.164387324 1.570531759 2.842663676 7.046515722 15.96872731 20.54645981 23.38066005 28.29761545 35.30450132 42.2961808  41.34020042 54.51721037 53.74564807 62.93070205 70.31965347 53.20712214 
 Uganda 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.008423042 0.018684872 0.022640286 0.131691862 0.239741703 0.522799789 1.130100554 1.516028656 2.892006194 4.195756068 4.578959089 6.761102482 13.65261655 26.92003559 28.55294653 37.74438345 47.50472743 45.00206351 
 List of countries: 
 What country do you want to search for?
 Belize
 Country Belize not found.

2 个答案:

答案 0 :(得分:2)

当您覆盖equals时,它必须是equals(Object),而不是equals(YourClassName)。你实际上还没有覆盖这个方法;您已经使用相同的名称制作了一个单独的方法,LinkedList不会打电话。

答案 1 :(得分:0)

回答新的回复,以便我可以引用代码。

回@LALA。这个特殊问题不是泛型,而是如何覆盖java.lang.Object中定义的密钥方法equals(Object)。要从基类重写方法,您必须获取签名点。容易搞砸,某处(java 1.4 ??)java添加了方法注释@Override。这告诉编译器(以及任何阅读代码的人......明天包括你)“此方法旨在覆盖基类(或接口)中的方法;如果不是,请抛出编译时错误,因为我已经f-ed了。

遵循此指南,您将输入:

//overrides the equals method and returns country name if found
@Overrides
public boolean equals(Country obj)
...

编译器会跳转并将其保存在此处,注意它不会覆盖任何内容。正确的是:

//overrides the equals method and returns country name if found
@Overrides
public boolean equals(Object obj)
...

我想补充一下......你已经提交了一个 major-java-developer-sin 。你曾[试图]写equals(),但你还没有覆盖hashCode()(再次指定@Override在这里更为重要(我个人经常忘记将'C'大写)。 )说真的,从不用另一种方法写出这两种方法中的一种。

作为此答案的作业,请仔细阅读以下内容:

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()