Java LinkedList contains()似乎失败了

时间:2017-03-27 08:15:30

标签: java list api

我正在尝试在进化算法中创建一个包含后代“最佳”的LinkedList。

因此,我有自己的自定义add()方法:

for(Virus parent : this.currentPopulation) {                                //for every virus in the current population
        for(GraphNode child : parent.getChildren()){                            //get all the children, and for each child
            temp = (Virus) child;   
            if(!temp.isDead() && !newCurrentPopulation.contains(child)) {       //try to add the child if it's not dead 
                newCurrentPopulation.add((Virus) child);                        //and not already in the list
            }                                                                   //(list only takes a maximum of <surviverPopulation>
        }                                                                       //and only the strongest ones, see declaration)
        newCurrentPopulation.add(parent);                                       //also try to add the parent to the list if
    }                                                                           //still alive

    int j = 0;
    for(Virus parent : this.currentPopulation) {                                //for every virus and its children in the current population
        for(GraphNode child : parent.getChildren()){                            //check if it made it into the new population
            if(!newCurrentPopulation.contains((Virus) child)) {
                toRemove.add((Virus) child);                                    //if not, memorize to delete it later
            }
        }
        if(!(newCurrentPopulation.contains((Virus) parent))); {
            toRemove.add(parent);                                               //do the same for the parent virus
        }
    }

使用这种方法,我得到一个有限大小的LinkedList,它也是有序的,只包含“最好的”对象。 (LinkedList类的其余部分未更改)。

然而,当我使用这个课时,会发生一些奇怪的事情:

public static obj operator+(obj a, obj b)
{
    a.magic += b.magic;
    return a;
}

它对孩子们来说很好,但不适合父母。调试信息显示即使父(可通过id标识)在newCurrentPopulation中,它也将被包含在toRemove列表中(它也可以通过相同的id识别)。

另外,我没有覆盖Virus-class或其任何超类的equals-method。我可能错过了一些非常明显的东西,但我看不到它。

2 个答案:

答案 0 :(得分:1)

确实非常明显:最后一个if语句后跟分号而不是{}。

答案 1 :(得分:0)

contains方法在内部调用equals类的Virus方法。 Object类提供的默认equals方法使用==运算符,在您的情况下返回false。 您必须覆盖equals类中的Virus方法,并将对象与id进行比较。