zoukankan      html  css  js  c++  java
  • java集合示例 小心重载的陷阱

    package com.hra.riskprice;
    
    import com.hra.riskprice.SysEnum.Factor_Type;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import java.util.*;
    @SpringBootApplication
    public class RiskpriceApplication {
    
        public static void main(String[] args) {
            Set<Integer> set=new TreeSet<>();
            List<Integer> list=new ArrayList<Integer>();
            for(int i=-3;i<3;i++){
    
                set.add(i);
                list.add(i);
            }
            System.out.println("remove 前:");//[-3, -2, -1, 0, 1, 2]
            System.out.println(set+" "+list);
            for(int i=0;i<3;i++){
                set.remove(i);//boolean remove(Object o);
                list.remove(i);//E remove(int index)
            }
    
            System.out.println("remove 后:");
            System.out.println(set+" "+list);
            //最终结果 set如预期因为调用的boolean remove(0bject 0)这个重载 移除了正数 剩下 -3,-2,-1
            //最终结果 list不如预期产生了混论 剩下 -2,0,2 原因见#list解释#
    
            //#list解释# list调用的是E remove(int index)这个重载 刚开始list有 :-3,-2,-1,0,1,2这些元素
            //这里我们标出了编号,每次remove后编号都会重新计算(很重要哦,这句话) -3(0),-2(1),-1(2),0(3),1(4),2(5)
            //list remove(0)  移除编号为0的元素后剩下     -2(0),-1(1),0(2),1(3),2(4)
            //list.remove(1)  移除编号为1的元素后剩下     -2(0),0(1),1(2),2(3)
            //list.remove(2)  移除编号为2的元素后剩下     -2(0),0(1),2(3)
            //#list解释#
    
            //如上我们分析出了list不如预期的原因,那么如何解决呢,让list.remove的时候调用boolean remove(Object o)这个重载呢,简单改为list.remove((Integer) i)就好了
        }
    }
  • 相关阅读:
    Ajax beforeSend和complete 方法与防止重复提交
    tablesorter周边文档
    对委托的一些短浅理解
    Nginx核心要领五:worker_processes、worker_connections设置
    二进制安装k8s 教程
    安装 Docker Engine-Community
    centos7.x 安装 NodeJS、yarn、pm2
    cfssl
    k8s各个进程 占用内存大小
    Linux下查看某一进程所占用内存的方法
  • 原文地址:https://www.cnblogs.com/kexb/p/10160707.html
Copyright © 2011-2022 走看看