In java, i have made (and am using without issues), this method:
private final HashMap<String, Object> data = new HashMap<>();
public final @NotNull <clazz> Collection<clazz> getCollection(@NotNull String key, @NotNull Object clazz) {
Object object = this.data.get(key);
if (object instanceof Collection) {
Collection<?> collection = (Collection<?>) object;
for (Object o : collection) {
if (o.getClass().equals(clazz)) {
return (Collection<clazz>) collection;
}
break;
}
}
return Collections.emptyList();
}
Specifically, the line return (Collection<clazz>) collection; is producing the warning:
Unchecked cast: 'java.util.Collection<capture<?>>' to 'java.util.Collection<clazz>'
Honesty where appropriate: i improvised this method out of neccessity about one year ago, shortly after i started learning to code. Unfortunately, even now, i still do not understand what exactly the <clazz> stuff i put there is doing, why it works and how it works.
In that sense: i'm looking to understand - not to be spoonfed the solution to remove the warning message, of course. (And i totally didn't use @SuppressWarnings("unchecked") prior to this post.)
/edit:
After reading the replies so far, i am in the ball park of understand why this warning is produced.
Now, for a theoretical workaround that should solve the problem:
public final @NotNull <T> Collection<T> getCollection(@NotNull String key, @NotNull Class<T> dataType) {
Object object = this.data.get(key);
Collection<T> r = new ArrayList<>();
if (object instanceof Collection) {
Collection<?> collection = (Collection<?>) object;
for (Object o : collection) {
if (o.getClass().equals(dataType)) {
r.add((T) o);
}
}
}
return r;
}
But now the line r.add((T) o); is producing the same warning. There must be a better condition other than o.getClass().equals(dataType) that will make the IDE understand. (IntelliJ Community Edition, by the way)