Java Collections replaceAll()方法及示例
java.util.Collections 类的 replaceAll() 方法是用来将一个列表中所有出现的指定值替换成另一个。更正式地说,用newVal替换列表中的每个元素e,以便
oldVal == null ? e==null : oldVal.equals(e)
注意: 这个方法对列表的大小没有影响。
参数: 该方法需要以下参数作为参数
- list: 要进行替换的列表。
- oldVal: 要被替换的旧值。
- newVal :要被替换的新值,即oldVal。
返回值: 如果列表中包含一个或多个元素e,该方法返回 真 ,否则返回假。
**oldVal== null** ? e==null : oldVal.equals(e)
Java
语法
public static boolean replaceAll(List list, T oldVal, T newVal)
Java
例1 :
// Java program to demonstrate
// replaceAll() method for String value
// Importing utility classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] argv) throws Exception
{
// Try block to check for exceptions
try {
// Creating a vector object of string type
List<String> vector = new Vector<String>();
// Populating the above Vector object
// Custom input elements
vector.add("A");
vector.add("B");
vector.add("A");
vector.add("C");
// Printing the vector
System.out.println("Initial Vector :" + vector);
// Replacing value
// using replaceAll() method
Collections.replaceAll(vector, "A", "TAJMAHAL");
// Printing elements of Vector object after
// replacing
System.out.println("Vector after replace :"
+ vector);
}
// Catch block to handle the exceptions
catch (IllegalArgumentException e) {
// Display message when exception occurs
System.out.println("Exception thrown : " + e);
}
}
}
Java
输出
Initial Vector :[A, B, A, C]
Vector after replace :[TAJMAHAL, B, TAJMAHAL, C]
Java
例2 :
// Java program to demonstrate
// replaceAll() method for Integer value
// importing utility classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] argv) throws Exception
{
// Try block to check for exceptions
try {
// Creating object of List<String>
List<Integer> vector = new Vector<Integer>();
// Populate the vector
vector.add(20);
vector.add(30);
vector.add(20);
vector.add(30);
// Printing the vector before replacing
// elements
System.out.println("Initial values are :"
+ vector);
// Replacing value
// using replaceAll() method
Collections.replaceAll(vector, 20, 400);
// Printing the vector after replacing elements
System.out.println("Value after replace :"
+ vector);
}
// Catch block to handle IllegalArgumentException
catch (IllegalArgumentException e) {
// Display the exceptions on the console
System.out.println("Exception thrown : " + e);
}
}
}
Java
输出
Initial values are :[20, 30, 20, 30]
Value after replace :[400, 30, 400, 30]
Java