I get a warning about unchecked casts on the “return (T) value;” line. Is there a better way to do this, or should I just suppress the warning?
class SomeClass<T>
{
/* ... other methods ... */
private Set<T> aSet;
public T filter(Object value)
{
if (this.aSet.contains(value))
return (T) value;
else
return null;
}
}
edit: I’m stuck with public T filter(Object value) as a signature.
Elaborating on Tom Hawtin’s answer, you have the option of using a
Map<T,T>instead, which gets around the casting issue. If you’re using aHashSet<T>foraSet‘s implementation,HashSetuses aHashMap<T,HashSet<T>>behind the scenes anyway (it uses references to itself as the values – not sure if there’s a reason for this other than choice – with the set’s “values” as keys) and performs the bulk of its operations just by reinterpreting the return values of theMapfunctions.Consequently, you could do this, if you wanted to (and I don’t see an immediate reason why it would be any less performant than a
HashSet):