I was wondering if it is possible that the general type of one class is determined by the generic type of another object passed as a parameter?
I am working on a stream iterator, so that multiple threads can safely use the iterator through a list without two streams receiving the same object. It works well in the current form, but I think it can be done a little better.
import java.util.Iterator; public class AtomicIterator implements Iterator<Object> { private Iterator<?> it; public AtomicIterator(Iterable<?> iterable) { it = iterable.iterator(); } public Object next() { synchronized(it) { if(it.hasNext()) return it.next(); else return null; } } }
Some of the code has been omitted, but this should be the idea. Currently, to get the next object, you are always forced to return a returned object that seems inefficient.
ArrayList<String> someList = new ArrayList<String>; AtomicIterator it = new AtomicIterator(someList); String example = (String)it.next();
The problem is that it.next() returns an Object type, where I want to return a String type in this example
A simple solution is to give AtomicIterator its own generic type, which will lead to something like
ArrayList<String> someList = new ArrayList<String>(); AtomicIterator<String> it = new AtomicIterator<String>(someList); String example = it.next();
However, this seems redundant to me, someList had its generic type explicitly defined as String , and I want AtomicIterator to AtomicIterator its generic type from the Iterable object that was given to it.
What I really want is something like this
import java.util.Iterator; public class AtomicIterator implements Iterator<E> { private Iterator<E> it; public <E> AtomicIterator(Iterable<E> iterable) { it = iterable.iterator(); } public E next() { synchronized(it) { if(it.hasNext()) return it.next(); else return null; } } }
And from there you can do something like
ArrayList<String> someList = new ArrayList<String>(); AtomicIterator it = new AtomicIterator(someList); String example = it.next();
But, alas, this does not work, because the generic type E exists only in the constructor area.
Does anyone know a good clean way to do this?