Why does the following code cause a warning when I try to compile it?
Bag.java:
import java.util.List;
public interface Bag<T> {
public List<String> getOwnerNames();
}
BagException.java:
public class BagException extends Exception {
public BagException(Bag badBag) {
super(buildMessage(badBag));
}
private static String buildMessage(Bag badBag) {
// BagException.java:10: warning: [unchecked] unchecked conversion
// List<String> owners = badBag.getOwnerNames();
// ^
// required: List<String>
// found: List
List<String> owners = badBag.getOwnerNames();
return "Something went wrong with the bag of " + String.join(", ", owners);
}
}
List<String> owners = badBag.getOwnerNames()
in buildMessage
causes the warning even though the method is declared to return List<String>
.
It seems really odd that these changes make the warning disappear:
Using
Bag<Integer> badBag
instead ofBag badBag
in argument ofbuildMessage
:private static String buildMessage(Bag<Integer> badBag) {
Using
Bag
instead ofBag<T>
in interface:public interface Bag {
I was expecting the method getOwnerNames
to be independant of the type T
of Bag
. It would be helpful if you could answer one of these questions:
- Why do I get a warning?
- What can I do about it other than suppressing it?