我想创建一个Pair
的String
和一个List
的String
的。
我创建了自己的类 Pair<String, List<String>>
。然而,当我尝试编译时,它提示括号。我应该怎样做才能消除这个错误?
error: > expected
static class Pair<String, List<String>> {
^
最佳答案
首先,我假设这个 Pair 类是一个静态嵌套类,如果不是,即使 Generic 声明可以,它仍然不会编译,因为顶级类不能是静态的。
这是关于如何声明泛型类的错误语法。
当您创建泛型类时,您不需要指定类的类型,因为这不是泛型的,并且它失去了它的全部目的,因此编译器将不允许它。
话虽如此,为了让你的代码正常工作并编译它,它会像下面这样:
import java.util.List;
public class Pair<T,S>{
private T t;
private S s;
//add revelevant code here
public static void main(String[] args){
//When instantiating the class you declare the generics types you want to use, in
//your case String,List<String>
Pair<String,List<String>> pair = new Pair<>();
//Since Java 7 we can use diamond operator <> in instantiation to infer the
//generic type otherwise it would be like this.
Pair<String,List<String>> otherPair = new Pair<String,List<String>>();
}
}
如果您对java中的泛型还有更多疑问,请访问https://docs.oracle.com/javase/specs/并找到所需 Java 版本的 Java 规范语言并检查泛型部分。
祝你有美好的一天!
关于java - 如何创建一对 String 和 List<String>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57948895/