关于List接口的remove(Object o)方法的对象与下标区分

import java.util.*;

public class Test14_1 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for(int i = 1; i <= 100; i++) {
            list.add(i);
        }
        Iterator<Integer> inte = list.iterator();
        while(inte.hasNext()) {
            Integer out = inte.next();
            System.out.print(out + " ");
        }
        
        System.out.println();
        
        //list.remove(list.get(10)); //*list。get(10)返回的是下标为10的对象,故remove改对象
        //list.remove((Integer)10);  //*remove“10”这个对象
        list.remove(10);             //*“10”为int型,故默认为下标,不会看成是对象,所以删除的是下标为10的对象
        //网上找到的解释……
        //*因为remove方法是一个被重载的方法,根据传入参数有int型(既下标索引)和Object(对象)型的两种方法,
        //*首先要知道直接输入一个整数如4,在没有声明变量类型的时候程序默认是int型,即使你在编译器里选用的是Object(对象)方法,
        //*程序运行时也是根据重载的机制以传入参数的类型而调用方法,因此list.remove(4)调用的是根据数组下标删除数据的方法,而非根据对象删除的方法,
        //*所以我们需要这样写:list.remove((Integer)4);这时4从int型被转为Integer型,程序运行时根据对象类型调用remove(Object)方法;
        
        Iterator<Integer> it = list.iterator();
        while(it.hasNext()) {
            Integer out = it.next();
            System.out.print(out + " ");
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值