【Java 1.8】LinkedList:checkElementIndex 和 checkPositionIndex 的疑惑

licjd 2020-07-15 08:45:57
在翻看 Java 1.8 源码发现,LinkedList 里面 checkElementIndex 和 checkPositionIndex 的实现基本一致,那是出于什么目的去实现两个方法呢?
源码:

/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}

/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}

/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}

private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
...全文
2588 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
usecf 2020-07-16
  • 打赏
  • 举报
回复
isElementIndex //Tells if the argument is the index of an existing element. isPositionIndex // Tells if the argument is the index of a valid position for an 看这两注释 一个是判断是否存在该元素 另外一个是索引越界

62,630

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧