Solution to solve Java collection immutable size exception (ImmutableSizeException)
When using Java collections, sometimes you will encounter immutable size exception (ImmutableSizeException) . This exception usually occurs when trying to modify the size of a collection, but the collection has been predefined as immutable. This article will introduce several solutions to this problem and give corresponding code examples.
import com.google.common.collect.ImmutableList; public class ImmutableCollectionExample { public static void main(String[] args) { ImmutableList<String> names = ImmutableList.of("Alice", "Bob", "Charlie"); // 尝试修改集合大小,将会抛出UnsupportedOperationException异常 names.add("David"); } }
import java.util.ArrayList; import java.util.List; public class CopyCollectionExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); // 创建副本进行操作 List<String> updatedNames = new ArrayList<>(names); updatedNames.add("David"); // 将结果赋值给原始集合 names = updatedNames; } }
import java.util.ArrayList; import java.util.List; public class MutableCollectionExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); // 修改集合大小 names.add("David"); } }
No matter which solution is chosen, it should be decided based on the specific needs and scenarios. If you only need to read the collection data without modifying it, immutable collections are a better choice. If the collection size needs to be changed frequently, mutable collections are more convenient. In addition, we must also pay attention to the operation of collections in a multi-threaded environment to ensure thread safety.
Summary:
Through the above solutions, the problem of Java collection size immutable exception (ImmutableSizeException) can be effectively solved and the reliability and stability of the program can be improved.
The above is the detailed content of Solution to Java collection size immutable exception (ImmutableSizeException). For more information, please follow other related articles on the PHP Chinese website!