这个问题说明了一切..
从列表的代码:
添加方法:
public boolean add(E e) { ... }
鉴于,删除方法:
public boolean remove(Object o) { .. }
这有什么具体原因吗?
这个问题说明了一切..
从列表的代码:
添加方法:
public boolean add(E e) { ... }
鉴于,删除方法:
public boolean remove(Object o) { .. }
这有什么具体原因吗?
从javadoc:
如果此列表不包含该元素,则保持不变
因此,在此处添加类型约束将毫无用处,而约束add
确保在编译时列表包含框上所写的内容。
请注意,由于允许该方法抛出一个
ClassCastException 如果指定元素的类型与此列表不兼容(可选)
ArrayList 实现不会抛出此异常:
439 public boolean remove(Object o) {
440 if (o == null) {
441 for (int index = 0; index < size; index++)
442 if (elementData[index] == null) {
443 fastRemove(index);
444 return true;
445 }
446 } else {
447 for (int index = 0; index < size; index++)
448 if (o.equals(elementData[index])) {
449 fastRemove(index);
450 return true;
451 }
452 }
453 return false;
454 }
这意味着您不必在执行删除操作之前检查原始对象的类别。