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

org.aksw.commons.accessors.CollectionFromSingleValuedAccessor Maven / Gradle / Ivy

There is a newer version: 0.9.9
Show newest version
package org.aksw.commons.accessors;

import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.Objects;

import org.aksw.commons.collections.SinglePrefetchIterator;

public class CollectionFromSingleValuedAccessor
	extends AbstractCollection
{
	protected SingleValuedAccessor accessor;

	public CollectionFromSingleValuedAccessor(SingleValuedAccessor accessor) {
		super();
		Objects.requireNonNull(accessor);
		this.accessor = accessor;
	}

	@Override
	public boolean add(T e) {
		Objects.requireNonNull(e);

		T value = accessor.get();
		// Added value must be reference equal
		if(value != null && value != e) {
			throw new RuntimeException("Cannot add because a value already exists: " + value);
		}
		accessor.set(e);
		return true;
	}
	
	@Override
	public Iterator iterator() {
		return new SinglePrefetchIterator() {
			T value = accessor.get();
			int emitted = 0;
			
			@Override
			protected T prefetch() throws Exception {
				
				return emitted++ != 0 || value == null ? finish() : value;
			}
			
			@Override
			protected void doRemove(T item) {
				accessor.set(null);
			}
		};		
	}

	@Override
	public int size() {
		T value = accessor.get();
		int result = value == null ? 0 : 1;
		return result;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy