I'm trying to implement Collection interface for study purpose. My add() and toArray() method looks like:
public class ArrayCollection<T> implements Collection<T> {
private T[] m = (T[])new Object[10];
private int size = 0;
@Override
public boolean add(final T t) {
m[size++] = t;
return true;
}
@Override
public Object[] toArray() {
T[] array = (T[]) new Object[size()];
int i = 0;
for (T item : ArrayCollection.this) {
array[i++] = item;
}
return array;
}
But when I perform testing:
@Test
public void testToArray() throws Exception {
final Collection<Integer> testInstance = new ArrayCollection<>();
testInstance.add(1);
testInstance.add(2);
testInstance.add(3);
final Integer[] result = testInstance.toArray();
assertEquals((Integer)1, result[0]);
assertEquals((Integer)2, result[1]);
assertEquals((Integer)3, result[2]);
assertEquals(3, result.length);
}
I get error:
ArrayCollectionTest.java:32: error: incompatible types: Object[] cannot be converted to Integer[]
final Integer[] result = testInstance.toArray();
I completelly don't uderstand how to fix this problem and what I'm doing wrong.