I'm trying to code something with generics, but cannot seem to figure out how to get around using a @SuppressWarnings.
I have the following:
/**
* Cache to know which pool provided which object (to know where to return object when done)
*/
private Map<Object, ObjectPool<?>> objectPoolCache = new ConcurrentHashMap<Object, ObjectPool<?>>();
/**
* Returns a borrowed pool object to the pool
* @param o
* @throws Exception
*/
public void returnToPool( Object o ) throws Exception {
// safety check to ensure the object was removed from pool using this interfact
if( !objectPoolCache.containsKey(o))
throw new IllegalStateException("Object is not in pool cache. Do not know which pool to return object to");
// get the object pool
ObjectPool pool = objectPoolCache.remove(o);
// return the object to the pool
pool.returnObject(o);
}
Right now, I get a warning that ObjectPool pool
is a raw type and a Type Safety warning on the return statement.
My concept is the following; I'm looking to make a map of object/pool pairs such that I know which pool an object was retrieved from in order to know to which pool to return the object.
The ObjectPool can be an ObjectPool of any type of object; there is no specific supertype required.
I've tried using <? extends Object>
, but I'm not entirely sure how to use it without causing compile errors. Just replacing the <?>
with <? extends Object>
runs me into a problem that my method uses an Object as a parameter, which is inconsistent with a pool that extends an Object.
Any assistance would be appreciated.
Thanks!
Eric
This is not doable without @SuppressWarnings
, just because Java's type system is not strong enough to express the constraint that your Map
maps any object of type T
to some ObjectPool<? super T>
.
Generics are designed to prove the type-safety of a wide variety of operations in Java, but they're just not powerful enough for what you're doing. You just have to tell the compiler to "trust that you know what you're doing," which is what @SuppressWarnings
is for.