在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.");
}
在處理這些異常時,應確保捕獲并適當處理它們,以防止程序意外終止。根據實際情況,可以選擇記錄錯誤、顯示錯誤消息或采取其他適當的措施。