Does this general method signature make sense?

Deprecated Code:

public <B extends IBox> List<B> getBoxList(String key)

The method does not know which subtype the expectant is really expecting, so there is no reasonable way to fulfill this contract.

Important: there is no way to infer the expected subtype from the key .

Therefore, the signature should be:

public List<IBox> getBoxList(String key)

Are my reasoning correct?

+4
source share
4 answers

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());//prints "RedBox"
    }
  }
}

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;
  }
}
0
source

You can easily do it like this:

public List<? extends IBox> getBoxList(String key)
0
source

. , . , , .

interface IBox {

}

public static <B extends IBox> List<B> getBoxList1(String key) {
    return null;
}

public static List<IBox> getBoxList2(String key) {
    return null;
}

class ABox implements IBox {

}

class BBox implements IBox {

}

public void test() {
    List<ABox> aBox = Test.<ABox>getBoxList1("Hello");
    List<BBox> bBox = Test.<BBox>getBoxList1("Hello");
    // Not allowed.
    List<ABox> cBox = Test.getBoxList2("Hello");
    List<IBox> dBox = Test.getBoxList2("Hello");
}
-1

,

public RedBox implements IBox{
//implementation here
}

public BlueBox implements IBox{
//implementation here
}

, RedBoxe YellowBox,

List<RedBox> redBoxList = getBoxList(redKey);
List<YellowBox> yellowBoxList = getBoxList(yellowKey);

:

List<RedBox> redBoxList = (List<RedBox>)getBoxList();//Since it returns List<IBox>
List<RedBox> redBoxList = (List<RedBox>)getBoxList();

, . . , " Java".

-1

All Articles