Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java list best practice

I need some container to keep elements so, if I'll try to get the size()+i element, i'll get element number i. Or with iterator, which starts from the beginning of container after it tries to get the last element? What are the best practicies in both cases? I mean performance and easy useability.

like image 830
Deepscorn Avatar asked Nov 25 '25 09:11

Deepscorn


2 Answers

You could create a simple subclass of ArrayList<T> and override the get(int n) method as follows:

public T get(int n)
{
    return super.get(n % this.size());
}

As to the iterator, you will need to implement your own, which shouldn't be all that hard.

EDIT:

Assuming your new class is called RingList, here's a sample RingIterator (untested):

public class RingIterator<T> implements Iterator<T>
{
    private int cur = 0;
    private RingList<T> coll = null;

    protected RingIterator(RingList<T> coll) { this.coll = coll; }
    public boolean hasNext() { return size() > 0; }
    public T next() 
    { 
        if (!hasNext()) 
            throw new NoSuchElementException();
        int i=cur++; 
        cur=cur%size(); 
        return coll.get(i);
    }
    public void remove() { throw new UnsupportedOperationException(); }
}

You would then override the iterator() method in RingList<T> as

public Iterator<T> iterator()
{
    return new RingIterator(this);
}
like image 70
Jim Garrison Avatar answered Nov 26 '25 22:11

Jim Garrison


For the first part, just ask for n % list.size() perhaps?

For the iterator part, create a class that wraps an iterator, and when next() returns null, just have it reset the iterator.

like image 36
Marvo Avatar answered Nov 26 '25 23:11

Marvo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!