List接口的特有方法(带索引的方法)

A:List接口的特有方法(带索引的方法)

   a:增加元素方法

   add(Object e):向集合末尾处,添加指定的元素

   add(int index, Object e)   向集合指定索引处,添加指定的元素,原有元素依次后移

 /*
       *  add(int index, E)
       *  将元素插入到列表的指定索引上
       *  带有索引的操作,防止越界问题
       *  java.lang.IndexOutOfBoundsException
       *     ArrayIndexOutOfBoundsException
       *     StringIndexOutOfBoundsException
       */
      public static void function(){
        List<String> list = new ArrayList<String>();
        list.add("abc1");
        list.add("abc2");
        list.add("abc3");
        list.add("abc4");
        System.out.println(list);
        
        list.add(1, "itcast");
        System.out.println(list);
      }

b:删除元素删除

   remove(Object e):将指定元素对象,从集合中删除,返回值为被删除的元素

   remove(int index):将指定索引处的元素,从集合中删除,返回值为被删除的元素

 /*
       *  E remove(int index)
       *  移除指定索引上的元素
       *  返回被删除之前的元素
       */
      public static void function_1(){
        List<Double> list = new ArrayList<Double>();
        list.add(1.1);
        list.add(1.2);
        list.add(1.3);
        list.add(1.4);
        
        Double d = list.remove(0);
        System.out.println(d);
        System.out.println(list);
      }
   c:替换元素方法
   set(int index, Object e):将指定索引处的元素,替换成指定的元素,返回值为替换前的元素
      /*
       *  E set(int index, E)
       *  修改指定索引上的元素
       *  返回被修改之前的元素
       */
      public static void function_2(){
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        
        Integer i = list.set(0, 5);
        System.out.println(i);
        System.out.println(list);
      }

d:查询元素方法

   get(int index):获取指定索引处的元素,并返回该元素

猜你喜欢

转载自blog.csdn.net/fang0321/article/details/83857293