【问题标题】:Instantiate ArrayList inside class constructor在类构造函数中实例化 ArrayList
【发布时间】:2013-11-07 19:28:01
【问题描述】:

我有一堂课如下:

package com.aci.golfgames;

import java.util.ArrayList;

public class Course {
    private String name;
    private int noOfTees;
    private ArrayList<Tee> tees;

    public Course(){
        // Build a course with some tees.
        name = "ABC Country Club";
        ArrayList<Tee> tees = new ArrayList<Tee>();
        tees.add(new Tee("White", 126, 70.4));
        tees.add(new Tee("Red", 128, 75.2));
        tees.add(new Tee("Blue", 126, 71.4));
        noOfTees = 3;
    }

    public String getCourseName(){
        return this.name;
    }
    public ArrayList<Tee> getTees(){
        return tees;
    }
    public int getNoOfTees(){
        return this.noOfTees;
    }
}

当我尝试实例化 ArrayList 字段 tees 时,似乎我创建的 ArrayList 与在对象 Course 中声明为字段的 ArrayList 不同。 IOW,this.teestees 不同。如果我删除该行:

            ArrayList<Tee> tees = new ArrayList<Tee>();

我在运行时在 tees.add(...) 处遇到空指针异常,我认为是因为 ArrayList 尚未实例化。

这里有什么问题?如何实例化 ArrayList?注意:tees ArrayList 中的条目数会因对象而异,因此 ArrayList 而不仅仅是一个数组。这里的代码只是定义一个Course用于测试。

谢谢。

【问题讨论】:

    标签: java arraylist


    【解决方案1】:
    public Course(){
        ArrayList<Tee> tees = new ArrayList<Tee>();
    }
    

    应该是

    public Course(){
        tees = new ArrayList<Tee>();
    }
    

    通过在构造函数中再次将其定义为ArrayList&lt;Tee&gt;,您将构造函数中tees 的范围缩小到仅构造函数,而其他方法使用tees,它被定义为实例中的字段范围。

    所以是的,它实际上会创建一个新列表,将在构造函数中使用。

    【讨论】:

      【解决方案2】:

      是的;您正在构造函数内部创建一个局部范围的ArrayList,它遮蔽了外部tee。你需要做的:

      tees = new ArrayList<Tee>();
      

      即去掉前面的ArrayList&lt;Tee&gt;

      对于tee的类型,还可以考虑使用接口List&lt;Tee&gt;而不是ArrayList&lt;Tee&gt;;由于您没有与ArrayList 紧密耦合,因此您以后可以轻松地交换实现。

      【讨论】:

      • 感谢您的快速回复。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多