HashSet中对象的问题

时间:2015-04-01 01:27:35

标签: java hashset

我创建了一个使用2个字符串的Console对象的HashSet。一个是控制台的公司名称,另一个是控制台名称。我对大多数基本方法没有任何问题(我知道如何添加到HashSet,清除HashSet等...),但我遇到了删除单个对象的问题,并检查HashSet是否包含某个对象。我已经包含了HashSet类的相关代码片段

   import java.util.HashSet;

    public class testHashSet
    {
    private HashSet <Console> testSet;

    /**
     * Constructor
     */
    public testHashSet()
    {
        testSet = new HashSet <Console> () ;
        setTestSet();
    }

    public void setTestSet(){
        testSet.add(new Console("Nintendo" , "Wii U"));
        testSet.add(new Console("Sony" , "PS4"));
        testSet.add(new Console("XBox" , "Microsoft"));
    }

    /**
     * Method to remove object from HashSet
     */
    public void removeData(){
        Console d = new Console("Sony" , "PS4");
        testSet.remove(d);
        printHashSet();
    }

    /**
     * Method to check for specific object in HashSet
     */
    public void checkForItem(String anyCompany, String anyConsole){
        boolean exist = testSet.contains(new Console (anyCompany, anyConsole));
        System.out.println(exist);
    }

编辑: 以下是Console类的源代码:

public class Console
{
private String companyName;
private String consoleName;

/**
 * Constructor for objects of class Console
 */
public Console(String anyCompany, String anyConsole)
{
    companyName = companyName;
    consoleName = anyConsole;
}

public void printConsoleInfo(){
    System.out.println(consoleName + " is a " + companyName + " console.");
}
}

1 个答案:

答案 0 :(得分:2)

您未在hashCode()课程中覆盖equals()Console

因此,您最终会使用java的默认实现,它会将Console的两个实例(并且您在方法中创建新实例)视为不同,即使您将相同的字符串传递给构造

要解决您的问题,您需要帮助&#34; java通过在equals()类中实现自定义Console方法来识别相等的对象。要遵守the general contract(并且由于HashSet尝试查找元素的方式),您还需要实现自定义hashCode()方法。

基本实现可以例如是

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((companyName == null) ? 0 : companyName.hashCode());
    result = prime * result
            + ((consoleName == null) ? 0 : consoleName.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Console other = (Console) obj;
    if (companyName == null) {
        if (other.companyName != null)
            return false;
    } else if (!companyName.equals(other.companyName))
        return false;
    if (consoleName == null) {
        if (other.consoleName != null)
            return false;
    } else if (!consoleName.equals(other.consoleName))
        return false;
    return true;
}

(由eclipse生成)

奖励:如果问题不是拼写错误,您还需要更改构造函数中的作业

companyName = companyName;

companyName = anyCompany;