java - 如何创建一对 String 和 List<String>?

标签 java data-structures

我想创建一个PairString和一个ListString的。

我创建了自己的类 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/

相关文章:

algorithm - 如果没有循环,如果权重为负,是否可以使用 Dijkstra 算法?

c++ - 使用动态分配数组和 realloc() 实现一些常见的 ADT

java - Eclipse:查找 Java 和 JSF/JSP 中的引用

java - Android XML 设计(布局)使我的应用程序如此缓慢

java - 无法在类外访问正确的类对象

asp.net - 网站数据库设计(CMS)考虑和数据库驱动菜单的建议

swift - 如何改进检查括号是否平衡的程序?

java - 在 java 矩阵中查找 "matches"的有效方法

java - 在 Amazon AWS 上启动 Spring Boot 应用程序,如何设置目标运行时

Java 枚举最佳实践