1

我该怎么做呢?因为你只能扩展一个类,所以它只能有一个上限。

就我而言,我需要将泛型类型限制在 String 和 int 中。如果我使用 Integer 包装器而不是 int 并依赖自动装箱,我可以做到,但问题是其他类也可以作为类型参数传递。

最好的方法是什么?

4

2 回答 2

5

您可以使用集合的非通用变体(例如 List),或者更明确List<Object>地显示代码的意图。
将其包装在 MyList 类中,并为您要支持的每种类型创建 add()、get() 方法:

add(Integer elem);
add(String elem);

但是 Object get() 不能被输入,所以它是有意义的。

所以最后你也可以将 Object 与 List 一起使用,并省略包装器。

于 2013-01-16T13:36:48.710 回答
0

我不认为你能做到。String 也是一个最终类和所有这些东西。正如@NimChimpsky 所说,使用 Object 本身可能会更好。另一个解决方案是两个类的包装器,但是您仍然会得到一个结果对象,您可能需要对其进行转换并依赖它instanceof

class StringInt {
  private String string;
  private Integer integer;

  public StringInt(String s) { this.string = s; }
  public StringInt(Integer i) { this.integer = i; }

  public Object getValue() { return string != null ? string : integer; }
}

或者使用丑陋的验证,显然,这只会在运行时应用......

class StringIntGen<T> {
  private T t;

  public StringIntGen(T t) { 
    if (!(t instanceof String) && !(t instanceof Integer)) 
      throw new IllegalArgumentException(
          "StringIntGen can only be Integer or String");
    this.t = t; 
  }

  public T getValue() { return t; }

}
于 2013-01-16T13:37:19.407 回答