【问题标题】:Way to access ArrayList from other method in same class without passing argument?在不传递参数的情况下从同一类中的其他方法访问 ArrayList 的方法?
【发布时间】:2016-02-08 19:24:30
【问题描述】:

我试图让我的方法“add”访问在方法“Friends”中创建的 ArrayList 的内容,但 Java 对我正在做的事情不满意(范围问题?)。有没有无需传递参数即可解决问题的方法?

public class Friends {
public Friends(float x, float y)
    {       
        ArrayList<MyObject> arrayList = new ArrayList<MyObject>(); 
        MyObject[] friendList = new MyObject[20];

    }

public void add()
    {       
        for (int i = 0; i < 20; i++) {
            //friendList[i]
        }
    }
}

请注意,Friends 是一个构造函数(如果我正确使用了这个词)

【问题讨论】:

  • friendList 应该是实例字段,而不是构造函数中的局部变量

标签: java arraylist scope arguments


【解决方案1】:

显然,对于这种情况,您应该使用所谓的“对象变量”,或者简单地说 - 类的字段。您应该将变量 arrayList 作为字段的一部分:

public class Friends {
List<MyObject> arrayList;
public Friends(float x, float y)
    {       
        arrayList = new ArrayList<MyObject>(); 
        MyObject[] friendList = new MyObject[20];

    }

public void add()
    {       
        for (int i = 0; i < 20; i++) {
            //arrayList.add(...).
        }
    }
}

【讨论】:

    【解决方案2】:

    将你的变量设为Friends类的成员变量:

    public class Friends {
    ArrayList<MyObject> arrayList;
    MyObject[] friendList;
    public Friends(float x, float y)
        {       
            arrayList = new ArrayList<MyObject>(); 
            friendList = new MyObject[20];
    
        }
    
    public void add()
        {       
            for (int i = 0; i < 20; i++) {
                //friendList[i]
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      你的猜测是正确的。这里的问题是范围界定。您正在构造函数中创建一个局部变量arrayList,该变量仅在构造函数中可用。

      你应该像这样将它声明为一个实例变量:

      public class Friends {
      
          ArrayList<MyObject> arrayList; = new ArrayList<MyObject>(); 
          MyObject[] friendList; = new MyObject[20];
      
          public Friends(float x, float y)
          {       
              this.arrayList = new ArrayList<MyObject>(); 
              this.friendList = new MyObject[20];
          }
      
      public void add()
      {       
          for (int i = 0; i < 20; i++) {
              //friendList[i]
          }
      }
      

      }

      【讨论】:

      • “全球”具有误导性。它是一个实例或成员变量。
      • 你说得对,我把它改成了实例变量。谢谢。
      猜你喜欢
      • 2018-07-06
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多