All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.qbcps.util.collections.RRDIterable Maven / Gradle / Ivy

There is a newer version: 2.7.1
Show newest version
package com.qbcps.util.collections;
/*
 * Copyright 8/3/18 by Stephen Beitzel
 */

import java.util.Iterator;

/**
 * 

This is a fixed-size collection that allows appending but not * deletion. For a collection of elements indexed 0 to N, adding the N+1th element * will result in a collection with elements 1 to N+1, with * the N+1 element overwriting the 0th element. This behavior is the * same as the data storage for RRDTool. *

*

This class is NOT thread safe. Clients requiring thread safety * should synchronize on the instance or on some other external lock. *

*

* Implementation note: this implementation is backed by an array. *

* * @author Stephen Beitzel <[email protected]> */ public class RRDIterable implements Iterable { private T[] _elements; private int _insertionPoint = 0; @SuppressWarnings("unchecked") public RRDIterable(int size) { _elements = (T[]) new Object[size]; for (int i = 0; i iterator() { return new RRDIterator(); } /** * Add an element to the collection, evicting the oldest element if necessary. * Nulls are allowed. * * @param element the element to add */ public void add(T element) { _elements[_insertionPoint++] = element; if (_insertionPoint >= _elements.length) { _insertionPoint = 0; } } public int size() { return _elements.length; } private class RRDIterator implements Iterator { private int _index; private int _startingPoint; private boolean _started = false; RRDIterator() { _index = _insertionPoint-1; if (_index < 0) { _index = _elements.length -1; } _startingPoint = _index; } @Override public boolean hasNext() { return !_started || _index != _startingPoint; } @Override public T next() { _started = true; T element = _elements[_index--]; if (_index <0) { _index = _elements.length-1; } return element; } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy