### Question:
PreAllocatedArray implements Iterable<T> { public T set(final int index, final T element) { return internal.set(index, element); } PreAllocatedArray(final int capacity); T set(final int index, final T element); T get(final int index); @Override Iterator<T> iterator(); final int length; }### Answer:
@Test public void testSet() { int capacity = 5; PreAllocatedArray<String> strings = new PreAllocatedArray<>(capacity); assertEquals(capacity, strings.length); strings.set(1, "a"); strings.set(4, "b"); assertEquals(capacity, strings.length); String b = strings.set(4, "c"); assertEquals("b", b); assertEquals(capacity, strings.length); Iterator<String> iter = strings.iterator(); assertNull(iter.next()); assertEquals("a", iter.next()); assertNull(iter.next()); assertNull(iter.next()); assertEquals("c", iter.next()); assertFalse(iter.hasNext()); }
@Test public void testSetIndexHigh() { PreAllocatedArray<String> strings = new PreAllocatedArray<>(3); strings.set(2, "in bounds"); assertThrows(IndexOutOfBoundsException.class, () -> strings.set(3, "out of bounds")); }
@Test public void testSetIndexNegative() { PreAllocatedArray<String> strings = new PreAllocatedArray<>(3); strings.set(0, "in bounds"); assertThrows(IndexOutOfBoundsException.class, () -> strings.set(-3, "out of bounds")); }