在Java中,add()
方法通常用于向集合(如List、Set等)添加元素。在处理异常时,需要考虑以下几种情况:
add()
操作时,会抛出此异常。例如,对于不可修改的集合(如通过Collections.unmodifiableList()
创建的列表),尝试调用add()
方法会导致此异常。List<String> list = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));
try {
list.add("d");
} catch (UnsupportedOperationException e) {
System.err.println("The add operation is not supported by this collection.");
}
Collections.checkedList()
创建的类型检查列表中添加错误类型的元素。List<Integer> checkedList = Collections.checkedList(new ArrayList<>(), Integer.class);
try {
checkedList.add("not an integer");
} catch (IllegalArgumentException e) {
System.err.println("The element type is not valid for this collection.");
}
List<String> stringList = new ArrayList<>();
try {
stringList.add(123); // Attempting to add an Integer to a List<String>
} catch (ClassCastException e) {
System.err.println("The element type is not valid for this collection.");
}
List<String> nonNullList = new ArrayList<>();
try {
nonNullList.add(null);
} catch (NullPointerException e) {
System.err.println("This collection does not allow null elements.");
}
add()
方法的索引形式(如list.add(index, element)
)并且指定了超出集合范围的索引时,会抛出此异常。List<String> list = new ArrayList<>();
try {
list.add(10, "out of bounds");
} catch (IndexOutOfBoundsException e) {
System.err.println("The specified index is out of bounds.");
}
在处理这些异常时,应确保捕获并适当处理它们,以防止程序意外终止。根据实际情况,可以选择记录错误、显示错误消息或采取其他适当的措施。