【问题标题】:How do I initialise a static List<T>?如何初始化静态 List<T>?
【发布时间】:2011-03-14 13:58:00
【问题描述】:

我似乎无法理解这个声明中出了什么问题

public static List<Vertex> vertices; 

// where Vertex is a class with a default constructor 

public static void main ( String [] arg ) throws IOException {
vertices = new List<Vertex>(); // eclipse complains
}

我应该在哪里以及如何初始化这个列表..... 因此,当我继续添加到列表中时,它会抱怨空指针异常.....谁能告诉我我做错了什么......

【问题讨论】:

  • 它给出了以下错误“无法实例化类型 List
  • 你确定可以编译吗? List是接口,不能实例化。
  • (强制说明可变静态是邪恶的。)

标签: java collections static initialization


【解决方案1】:

List 是一种抽象类型,由各种类型的列表扩展和实现。 请尝试以下操作:

    public static void main ( String [] arg ) throws IOException {
         vertices = new ArrayList<Vertex>(); 
    }

【讨论】:

    【解决方案2】:

    List 是一个接口,不能被实例化。请改用 ArrayList 或 LinkedList。

    vertices = new ArrayList<Vertex>();
    

    【讨论】:

      【解决方案3】:

      列表是一个接口。您需要使用实现List的类,例如ArrayList。

      【讨论】:

        【解决方案4】:

        试试:

        vertices = new ArrayList<Vertex>();
        

        List是Java中的一个接口,所以你需要使用它的一个实现。

        http://download.oracle.com/javase/6/docs/api/java/util/List.html

        【讨论】:

          【解决方案5】:

          List 不是类,而是接口。由于接口不是任何可以实例化的东西的完整具体实现。您只能对非抽象类执行新操作。所以尝试实例化ArrayList 或其他实现。

          【讨论】:

            【解决方案6】:

            你需要使用一个List的实现,比如:

            vertices = new ArrayList<Vertex>();
            

            【讨论】:

              【解决方案7】:

              Eclipse 抱怨是因为 List 不能被实例化,因为它是一个接口而不是一个具体的类。 您在这里有两个选择-

              选项 1:

              public static List<Vertex> vertices; 
              
              // where Vertex is a class with a default constructor 
              
              public static void main ( String [] arg ) throws IOException {
              vertices = new ArrayList<Vertex>(); // eclipse does not complain
              }
              

              选项2:

              public static List<Vertex> vertices=new ArrayList<Vertex>(); 
              
              // where Vertex is a class with a default constructor 
              
              public static void main ( String [] arg ) throws IOException {
              v
              }
              

              【讨论】:

                猜你喜欢
                • 2016-08-22
                • 2023-03-23
                • 2013-04-29
                • 1970-01-01
                • 2021-04-05
                • 1970-01-01
                • 2010-10-05
                • 1970-01-01
                相关资源
                最近更新 更多