Java.util.Collections 类

java.util.Collections.replaceAll() 方法用于将列表中出现的所有指定值替换为其他。

语法

public static <T> boolean replaceAll(List<T> list,
                                     T oldVal,
                                     T newVal)

这里,T是列表中元素的类型。

参数

list 指定要进行替换的列表。
oldVal 指定要替换的旧值。
newVal 指定oldVal要替换的新值

返回值

如果 list 包含一个或多个元素 e 且满足 (oldVal==null ? e= =null : oldVal.equals(e))。

Exception

如果指定的列表或其列表迭代器不支持该集合,则抛出UnsupportedOperationException

示例:

下面的示例中,使用java.util.Collections.replaceAll()方法来替换给定列表中指定元素与新元素的所有出现。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建列表对象
    List<Integer> MyList = new ArrayList<Integer>();

    //填充我的列表
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(10);
    MyList.add(10);
    MyList.add(10);
    MyList.add(60);

    //打印我的列表
    System.out.println("MyList contains: " + MyList); 

    //用 25 替换所有出现的 10
    Collections.replaceAll(MyList, 10, 25);

    //打印我的列表
    System.out.println("MyList contains: " + MyList); 
  }
}

上述代码的输出将是:

MyList contains: [10, 20, 30, 10, 10, 10, 60]
MyList contains: [25, 20, 30, 25, 25, 25, 60]