【问题标题】:Can't add to arrayList in method无法在方法中添加到 arrayList
【发布时间】:2015-01-16 01:51:03
【问题描述】:

由于某种原因,我无法从我的主类中的其他方法访问我在程序的主方法中创建的 arrayList。

public static void main(String[] args) {
    //creating array list for vehicles
    ArrayList<motorVehicle> vehicleList = new ArrayList<motorVehicle>();
    getAndCheckMainSelection();

在我为我的对象收集输入的最后,我去创建和添加值,它在 netbeans 中给出了一个错误,说找不到突出显示车辆列表的变量..

vehicleList.add(new car(wheels, engineSize, valueOfPS, date, serialNumber, doors, color));

【问题讨论】:

  • 阅读变量 scope
  • 您确定 new car() 中的所有这些变量都存在吗?如果你做 car newcar = New car(wheels, engineSize, valueOfPS, date, serialNumber, door, color); vehicleList.add(newcar);
  • 一种方法中的变量对其他方法不可见。将它们设为字段,或将它们作为参数传递。
  • 这是基本的 Java。你没有专心听课。
  • 我做到了,但我认为我把我的问题分解了很多。我没有使用不同的方法来选择添加删除车辆以及它们是什么子类,而是将其捆绑在我的主要方法中,并且我的创建方法(汽车、卡车等)返回该类型以添加​​到车辆列表中在 main 方法中。

标签: java oop arraylist


【解决方案1】:

vehicleList 是局部变量,你只能在声明它们的方法中访问局部变量,如果你想在另一个方法中使用vehicleList,你应该将它声明为实例变量、类变量或作为参数传递。你可以在docs阅读更多关于它们的信息

【讨论】:

  • 您是对的,但您的答案缺少关键字。 范围.
【解决方案2】:

您正在尝试将数据(条目)添加到仅存在于 void 主类中的变量中。使 vehicleList 变量存在于类 Scope 中,以便所有方法都可以访问它(静态除外)

【讨论】:

    【解决方案3】:

    我认为您希望您的 arrayList 对所有方法都可见。在这种情况下。像这样使用它:

    public class Myclass {
    
    private static ArrayList<motorVehicle> vehicleList = new ArrayList<motorVehicle>(); //has to be static to be accessed in static methods
    
    public static void main(String[] args) {
    //Do your stuff
    
    getAndCheckMainSelection();
    
    }
    

    如您所见,我将 vehicleList 声明为私有。这意味着它可以在任何地方使用,但只能在这个类中使用!

    【讨论】:

    • 如何在静态方法中访问非静态对象?
    猜你喜欢
    • 1970-01-01
    • 2014-09-26
    • 2018-09-18
    • 1970-01-01
    • 2018-12-09
    • 2020-12-03
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多