简体   繁体   中英

Accesing a static ArrayList from another class in Java

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< **cityList.size();** i++) {
            
}

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

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 < cityList.size(); i++) {
    // code
}

Or just use it directly from that method:

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

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 < CityMenuCreate.getCityList().size(); i++) {
     //Your code goes here
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM