相关疑难解决方法(0)

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

问题:

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

java generics raw-types

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

泛型类中的Java泛型方法

如果在Java中创建泛型类(该类具有泛型类型参数),您可以使用泛型方法(该方法采用泛型类型参数)吗?

请考虑以下示例:

public class MyClass {
  public <K> K doSomething(K k){
    return k;
  }
}

public class MyGenericClass<T> {
  public <K> K doSomething(K k){
    return k;
  }

  public <K> List<K> makeSingletonList(K k){
    return Collections.singletonList(k);
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您所期望的泛型方法,我可以调用任何对象的doSomething(K)实例MyClass:

MyClass clazz = new MyClass();
String string = clazz.doSomething("String");
Integer integer = clazz.doSomething(1);
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使用MyGenericClass 没有指定泛型类型的实例,我调用doSomething(K)返回一个Object,无论K传入什么:

MyGenericClass untyped = new MyGenericClass();
// this doesn't compile - "Incompatible types. Required: String, Found: Object" …
Run Code Online (Sandbox Code Playgroud)

java generics language-design raw-types generic-method

29
推荐指数
1
解决办法
7770
查看次数

为什么使用泛型类作为原始类型会杀死所有包含的泛型?

为什么

class Foo<T> {
}

class Bar<T> {
   List<Foo<?>> getFoos() {
      return null;
   }
}

class Baz {
   void baz(Bar bar) {
      for (Foo foo : bar.getFoos()); 
//                              ^
//error: incompatible types: Object cannot be converted to Foo
   }
}
Run Code Online (Sandbox Code Playgroud)

给出编译器错误

class Foo<T> {
}

// changed Bar<T> to Bar
class Bar {
   List<Foo<?>> getFoos() {
      return null;
   }
}

class Baz {
   void baz(Bar bar) {
      for (Foo foo : bar.getFoos());
   }
}
Run Code Online (Sandbox Code Playgroud)

class Foo<T> {
}

class …
Run Code Online (Sandbox Code Playgroud)

java generics

7
推荐指数
0
解决办法
124
查看次数

为什么javac抱怨与类的类型参数无关的泛型?

请按顺序阅读代码中的注释,问题详情如下.
为什么会发生这种差异?
如果可能,请引用JLS.

import java.util.*;

/**
 * Suppose I have a generic class
 * @param <T> with a type argument.
 */
class Generic<T> {
    // Apart from using T normally,
    T paramMethod() { return null; }
    // the class' interface also contains Generic Java Collections
    // which are not using T, but unrelated types.
    List<Integer> unrelatedMethod() { return null; }
}

@SuppressWarnings("unused")
public class Test {
    // If I use the class properly (with qualified type arguments)
    void properUsage() { …
Run Code Online (Sandbox Code Playgroud)

java generics javac unchecked

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