zoukankan      html  css  js  c++  java
  • 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的效果,结果是错误的。

  • 相关阅读:
    使用Dockerfile构建镜像并push到私有仓库
    docker registry-v2 搭建私有仓库
    spring-cloud 学习四 服务网关
    spring-cloud 学习三 服务提供者
    TortoiseSVN安装和使用
    SG-UAP常用注解介绍
    weblogic漏洞
    开发工具历史版本
    Android Studio 打包生成apk
    weblogic unable to get file lock问题
  • 原文地址:https://www.cnblogs.com/yuwenfeng/p/4209959.html
Copyright © 2011-2022 走看看