您的位置:首页 > 移动开发 > Objective-C

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

2018-03-06 20:50 525 查看
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 + " ");
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 集合
相关文章推荐