Circular ArrayList (extending ArrayList)
So my program has a need of a type of circular ArrayList.
Only circular thing about it has to be the get(int index) method, this is
the original:
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
If index is -1 it should get the element with index ArrayList.size()-1 and
if index is ArrayList.size(), it should get the element with index 0.
Simplest way of achieveing this which came to my mind is simply extending
ArrayList from the java.util package and just overriding the get(int
index) so it does not throw IndexOutOfBoundsException for the two indexes
above, but change them to what I want. It would throw
IndexOutOfBoundsException for any other index that is out of bounds.
However, since elementData(index) access a
private transient Object[] elementData;
I cannot make it work, because my class doesn't see it since it's private.
Also, I don't want to use any external libraries for this, simply because
I think there are none that suit my needs, since I don't want a real
circularArray, but only a part of it's functionality, rest of it being of
the regular ArrayList.
So I have two questions:
How can I make this work? Is there a way to do it without copying the
whole ArrayList class along with AbstractCollection, Collection and
Iterable into my program? That seems like bad design even to me.
If I can somehow make it work, is there anything else I should watch for?
If I make the changes described above, would that change the behaviour of
the class only the way I want it to, or could there be any other undesired
behaviour changes?
EDIT: Thanks for the answer, here's what I've done:
import java.util.ArrayList;
public class CircularArrayList<E> extends ArrayList<E>
{
private static final long serialVersionUID = 1L;
public E get(int index)
{
if (index == -1)
{
index = size()-1;
}
else if (index == size())
{
index = 0;
}
return super.get(index);
}
}
No comments:
Post a Comment