访问 Java 中另一个类中的静态 ArrayList。

huangapple go评论79阅读模式
英文:

Accesing a static ArrayList from another class in Java

问题

以下是翻译好的内容:

ArrayList 需要设置为静态。我在主类(CityMenuCreate)中创建了一个 getter 方法。在第二个类中,我调用了这个方法,当我尝试创建一个 for 循环时,它无法识别这个列表。

我在第一个类(CityMenuCreate)中创建的方法:

public static ArrayList getCityList() {
    return cityList;
}

我试图在第二个类中调用该方法的代码部分:

CityMenuCreate.getCityList();
for(int i=0; i< **cityList.size();** i++) {
    
}

cityList.size(); 这一部分出现错误。在这个 for 循环函数中是否存在语法问题?

英文:

The ArrayList needs to be set to static. I created a getter method in the main class (CityMenuCreate).In the second class, I do call the method and when I try to create a for function, it doesn't recognize the list.

The method I created in the first class (CityMenuCreate)

public static ArrayList getCityList() {
	return cityList;
}

The part of code I'm trying to call the method in the second class

CityMenuCreate.getCityList();
for(int i=0; i&lt; **cityList.size();** i++) {
			
}

It gives me an error in the cityList.size();. Is there a syntax problem in the for function?

答案1

得分: 1

你正在忽略 CityMenuCreate.getCityList() 的返回值。你需要将其保存到一个局部变量中:

List cityList = CityMenuCreate.getCityList();
for (int i = 0; i < cityList.size(); i++) {
    // 代码
}

或者直接从该方法中直接使用:

for (int i = 0; i < CityMenuCreate.getCityList().size(); i++) {
    // 代码
}
英文:

You're ignoring the return value of CityMenuCreate.getCityList(). You either need to save it to a local variable:

List cityList = CityMenuCreate.getCityList();
for (int i = 0; i &lt; cityList.size(); i++) {
    // code
}

Or just use it directly from that method:

for (int i = 0; i &lt; CityMenuCreate.getCityList().size(); i++) {
    // code
}

答案2

得分: 1

在上面的示例中,您已将 getCityList() 方法声明为静态方法,而不是您的 Arraylist。因此,您无法以静态方式访问您的 Arraylist。您可以将 Arraylist 声明为静态,或者在您的 for 循环中像这样调用该方法:

for (int i = 0; i < CityMenuCreate.getCityList().size(); i++) {
    //在这里编写您的代码
}
英文:

In the above example, you've declared your getCityList() method as static, not your Arraylist. Hence you cannot access your Arraylist in a static way. You either declare your Arraylist static or in your for loop you call the method like so:

 for (int i = 0; i &lt; CityMenuCreate.getCityList().size(); i++) {
     //Your code goes here
 }

huangapple
  • 本文由 发表于 2020年8月22日 09:26:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63531740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定