自定义ArrayList指定位置添加元素JUnit测试失败排查求助
自定义ArrayList指定位置添加元素的JUnit测试失败排查与修复
一、测试用例的直接错误
你的失败测试用例最后一个断言存在逻辑错误:
assertEquals(2, list.getSize()); // Check if the size of the list is 2 after the addition
实际执行了3次添加操作:
list.add(0, 10)→ 列表size变为1list.add(1, 20)→ 列表size变为2list.add(1, 40)→ 列表size变为3
正确的断言应为:
assertEquals(3, list.getSize());
二、add方法的泛型实现问题
你的CustomArrayList是泛型类,但指定位置添加的方法参数使用了Object element,违背泛型设计规范:
- 失去编译期类型检查,可能存入不符合泛型约束的元素
- 调用
get方法时需强制类型转换,易引发ClassCastException
修正后的泛型版add方法:
public boolean add(int index, E element) { // 边界合法性检查 if (index < 0 || index > size) { throw new IndexOutOfBoundsException("Index out of bounds"); } // 数组满时扩容 if (size == items.length) { increaseCapacity(); } // 从后往前右移元素,腾出指定位置 for (int i = size - 1; i >= index; i--) { items[i+1] = items[i]; } // 插入新元素并更新size items[index] = element; size++; return true; }
同时要确保类内数组定义为泛型数组:private E[] items;,初始化可通过(E[]) new Object[initialCapacity]实现。
三、配套方法的正确性验证
需确认get和getSize方法实现无误:
getSize直接返回维护的size变量:
public int getSize() { return size; }
get方法做边界检查后返回泛型元素:
public E get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index out of bounds"); } return items[index]; }
修正后的完整测试用例
补充对右移元素的验证,让测试更全面:
@Test public void addAtPosition() { CustomList<Integer> list = new CustomArrayList<>(); list.add(0, 10); list.add(1, 20); assertEquals(Integer.valueOf(10), list.get(0)); assertEquals(Integer.valueOf(20), list.get(1)); list.add(1, 40); assertEquals(Integer.valueOf(40), list.get(1)); assertEquals(Integer.valueOf(20), list.get(2)); // 验证原元素被正确右移 assertEquals(3, list.getSize()); }
内容的提问来源于stack exchange,提问作者Saurav Bhatt
相关产品推荐
相关产品推荐

