相关疑难解决方法(0)

什么是原始类型,为什么我们不应该使用它?

问题:

  • 什么是Java中的原始类型,为什么我经常听说不应该在新代码中使用它们?
  • 如果我们不能使用原始类型,它有什么替代方案,它是如何更好的?

java generics raw-types

617
推荐指数
13
解决办法
20万
查看次数

快速java泛型问题

我不认为我真的了解Java泛型.这两种方法有什么区别?为什么第二个没有编译,错误如下所示.

谢谢

static List<Integer> add2 (List<Integer> lst) throws Exception {
    List<Integer> res = lst.getClass().newInstance();
    for (Integer i : lst) res.add(i + 2);
    return res;
}
Run Code Online (Sandbox Code Playgroud)

.

static <T extends List<Integer>> T add2 (T lst) throws Exception {
    T res = lst.getClass().newInstance();
    for (Integer i : lst) res.add(i + 2);
    return res;
}

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types
  required: T
  found:    capture#1 of ? extends java.util.List
Run Code Online (Sandbox Code Playgroud)

java generics

4
推荐指数
1
解决办法
360
查看次数

标签 统计

generics ×2

java ×2

raw-types ×1