- 首先,List是一个接口,是一个继承了Collection接口的接口。。。并定义扩展了自己的方法。
- 打开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())); } }
-
这个方法之前也见过,但是不是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]
-
接下来是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]
-
发现与以往用的方法很大不同,它真的是全部替换。
-
最后,List源码并不能看出什么重要的东西,主要还是去它的实现类里去看。