• 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)就好了
        }
    }
  • 相关阅读:
    Bootstrap-select 动态绑定值
    Centos 下载
    设置图片大小和旋转
    aolication全局传递参数
    Activity静态变量传递参数
    Activity传递参数
    Activity横屏后声明周期的变化
    Intent隐式意图
    Intent显示意图的四种跳转
    SharedPreferences简单的应用
  • 原文地址:https://www.cnblogs.com/kexb/p/10160707.html
Copyright © 2020-2023  润新知