I was given the task to write my wrapper on an array. But I ran into the problem of a generic job. The fact is that I need to have a dynamic structure, and for example, I wanted to write an addition like this:

public class SimpleArray<E> extends ArrayIterator<E> implements Simple<E> { @Override public boolean add(E o) { // values это массив значений от итератора унаследован. values = new E[values.length + 1]; // проблема! ... } 

I have a problem that I cannot create an object of type new E[] , but I need to increase the size somehow. But, the task itself is on generics and I need to work with indefinite types ... Help please. What are the ways out? How do I create an array with a length longer than it is?

  • Are you doing an array or iterator? - Mikhail Vaysman
  • 2
    Store in Object[] and cast in return operations, ArrayList does just that. Everything is quite complicated there and other solutions will not be very productive. - etki
  • >>> Are you making an array or an iterator? <<< I do my wrapper to use an array as a dynamic structure. - Pavel

1 answer 1

As already suggested by @etki, you need to expand the array by creating Object[] :

 public class SimpleArray<E> extends ArrayIterator<E> implements Simple<E> { E[] values; @Override public boolean add(E o) { // values это массив значений от итератора унаследован. values = (E[])new Object[values.length + 1]; ... } }