No, it is not. Consider the following code, which will not even compile under Java 8, but will compile under Java 7 with a warning. The caller is actually expecting a list of BlueBox from BoxDB:
List<BlueBox> boxList = boxDB.<BlueBox>getBoxList("123");
But what it actually gets is a RedBox list. Thus, the method does not convey what it promises.
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
BoxDB boxDB = new BoxDB();
List<BlueBox> boxList = boxDB.<BlueBox>getBoxList("123");
for (IBox box: boxList) {
System.out.println(box.getClass().getName());
}
}
}
interface IBox {
String getKey();
}
class RedBox implements IBox {
String key;
public RedBox(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
class BlueBox implements IBox {
String key;
public BlueBox(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
class BoxDB
{
public <B extends IBox> List<B> getBoxList(String key) {
List<B> result = new ArrayList<>();
result.add((B)new RedBox("123"));
return result;
}
}
source
share