[英]Why not IndexOutOfBoundsException on List.subList(size, size)?
我在看List.subList()方法。 我想知道為什么以下代碼不會引發IndexOutOfBoundsException。
ArrayList<String> someList = new ArrayList<>();
someList.add("A");
someList.add("B");
someList.add("C");
someList.add("D");
someList.add("E");
someList.subList(5, 5);
文檔說subList是subList(fromIndex,toIndex),其中fromIndex包含在內。 由於我的list.size()是5,所以索引從0到4。所以,如果fromIndex是包容性的,不應該拋出異常嗎?
從文檔:
fromIndex - low endpoint (inclusive) of the subList
toIndex - high endpoint (exclusive) of the subList
IndexOutOfBoundsException - for an illegal endpoint index value (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
我在這里了解布爾表達式。 但是不應該是(... || fromIndex> = toIndex)嗎?
我想念什么?
您可以准確地檢查ArrayList
的實現IndexOutOfBoundsException的標准是:
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}
因此,您可以看到,由於toIndex == size
,因此不會引發異常。
為了考慮API設計者為何決定采用這種方式的決定,我們可以舉一個String.substring()
為例,它具有非常相似(相同)的約束。 可能允許選擇一個空字符串/子列表?
此外, 文檔還確認了以下假設:
(如果
fromIndex
和toIndex
相等,則返回的列表為空。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.