JAVA源码List源码解读

  1. 首先,List是一个接口,是一个继承了Collection接口的接口。。。并定义扩展了自己的方法。
  2. 打开java8中List的源码,可以看到,它重写了许多父类的方法。普通的abstract方法平常用的多,暂时不解析。在源码中看到这样一个方法:
     default void replaceAll(UnaryOperator<E> operator) {
            Objects.requireNonNull(operator);
            final ListIterator<E> li = this.listIterator();
            while (li.hasNext()) {
                li.set(operator.apply(li.next()));
            }
        }

     

  3. 这个方法之前也见过,但是不是List的,是Collections.replaceAll()方法;

    import java.util.*;
     
    public class Main {
       public static void main(String[] args) {
          List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
          System.out.println("List :"+list);
          Collections.replaceAll(list, "one", "hundrea");
          System.out.println("replaceAll: " + list);
       }
    }
    
    
    以上代码运行输出结果为:
    
    List :[one, Two, three, Four, five, six, one, three, Four]
    replaceAll: [hundrea, Two, three, Four, five, six, hundrea, three, Four]

     

  4. 接下来是List.replaceAll()的实现;

    import java.util.function.*;
    
    class MyOperator<T> implements UnaryOperator<T>{
     T varc1;
     public T apply(T varc){
      return varc1;
     }
    }
    
    import java.util.*;
    
    public class test {
      public static void main(String[] args) {
     
      ArrayList<String> color_list;
      MyOperator<String> operator;
      
      color_list = new ArrayList<> ();
      operator = new MyOperator<> ();
      
      operator.varc1 = "White";
      
     // use add() method to add values in the list
        color_list.add("White");
        color_list.add("Black");
        color_list.add("Red");
        color_list.add("White");
    	color_list.add("Yellow");
    	color_list.add("White");
      
        System.out.println("List of Colors");
        System.out.println(color_list);
      
     // Replace all colors with White color 
        color_list.replaceAll(operator);
        System.out.println("Color list, after replacing all colors with White color :");
        System.out.println(color_list);    
     }
    }
    
    //输出结果
    List of Colors
    [White, Black, Red, White, Yellow, White]
    Color list, after replacing all colors with White color :
    [White, White, White, White, White, White]

     

  5. 发现与以往用的方法很大不同,它真的是全部替换。 

     

  6. 最后,List源码并不能看出什么重要的东西,主要还是去它的实现类里去看。 

     

     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值