Collections.replaceAll方法用于替换List中所有与旧值相等的元素为新值,返回是否发生替换。
在Java中,Collections.replaceAll 是一个静态方法,用于替换集合中所有与指定旧值相等的元素为新值。这个方法属于 java.util.Collections 工具类,适用于任何实现了 List 接口的集合(如 ArrayList、LinkedList 等)。
方法签名:
public static
该方法返回 boolean 类型,如果集合中至少有一个元素被替换则返回 true,否则返回 false。若 oldVal 和 newVal 相等(通过 equals 比较),不会进行实际替换,也返回 true。
以下是一个简单的使用案例:
import java.util.*;
public class ReplaceExample {
public static void main(String[] args) {
List words = new ArrayList<>();
words.add("apple");
words.add("banana");
words.add("apple");
words.add("cherry");
// 将所有 "apple" 替换为 "orange"
boolean result = Collections.replaceAll(words, "apple", "orange");
System.out.println("替换成功: " + result); // 输出 true
System.out.println(words); // [orange, banana, orange, cherry]
}
}
对于自定义对象,确保重写了 equals 方法:
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person per
son = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public String toString() {
return name + "(" + age + ")";
}
}
使用 replaceAll 替换 Person 对象:
Listpeople = new ArrayList<>(); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); people.add(new Person("Alice", 25)); Collections.replaceAll(people, new Person("Alice", 25), new Person("Carol", 28) ); System.out.println(people); // [Carol(28), Bob(30), Carol(28)]