ArrayList中contains,remove方法返回为false的原因

这几天做一个项目时,遇到ArrayList.remove(Object)方法失败,而ArrayList"包含"删除的对象,这其中的"包含"不是完全包含,请看下面的例子:

package org.mytest;

import java.util.ArrayList;

/**对ArrayList.remove或者contains的笔记
 * contains,remove时会执行equals()
 * 例子1,删除为false
 * 例子2,删除为true
 * @author ywf
 *
 */
public class test {
public static void main(String[] args) {
    System.out.println("例子1:ArrayList删除Node对象:");
    ArrayList<Node> list = new ArrayList<Node>();
    Node node1 = new Node(1);
    Node node2 = new Node(2);
    list.add(node1);
    list.add(node2);
    System.out.println(list.remove(new Node(1)));
    System.out.println("例子2:ArrayList删除Integer对象:");
    ArrayList<Integer> list1 = new ArrayList<Integer>();
    Integer node11 = new Integer(1);
    Integer node21 = new Integer(2);
    list1.add(node11);
    list1.add(node21);
    System.out.println(list1.remove(new Integer(1)));
}
}
class Node{
    int id;
    public Node(int id){
        this.id = id;
    }
    public boolean equals(Node node){
        return this.id==node.id;
    }
}

有经验的可以一下子得出第一个是false,第二个是true,对我这个菜鸟来说以为两个都是true,我以为覆写了equals()就能实现都为true的效果,结果是错误的。

posted on 2015-01-08 09:11  ywf—java  阅读(1306)  评论(0编辑  收藏  举报

导航