简体   繁体   中英

Java: Import array of Strings from another class

I did not understand other answers in other threads, so here goes this question:

How do I import an array of strings from one class to another? The list is quite long, which makes it look bad all in one class with the methods.

This is how it looks:

List<String> countriesList = new ArrayList<>(
    Arrays.asList("Japan", 
                  "Sweden", //Etc...

I also have another that is connected to it (it's a guess country and city game and the country is randomized by math.random).

List<String> huvudList = new ArrayList<>(
    Arrays.asList(
        "Tokyo",
        "Stockholm", //Etc...

So how do I put these lists in another class, import them to my main class and use them normally (So I am still able to randomize a random value to the list, etc..). Are there any pretty ways to do this or should I stick with what I got?

This is how I began the class in which I will put the lists:

Why do I get an error when doing this? In what way is it wrong? (ListaLandQuiz is the class and countriesList is the list). It says The method countriesList(int) is undefined for the type ListaLandQuiz

  package Games;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;


public class Experiments {

    public static void main(String[] args) {
        // Importing classes

        System.out.println(ListaLandQuiz.countriesList(3));

    }

}

Thanks in advance.

Assuming you want the lists to be shared and immutable, just make them public and static:

public final class MyLists {

    public static final List<String> COUNTRIES = Collections.unmodifiableList(Arrays.asList(
            "Japan", 
            "Sweden",
            //Etc..
    ));

    public static final List<String> CAPITALS = Collections.unmodifiableList(Arrays.asList(
            "Tokyo",
            "Stockholm",
            //Etc...
    ));

}

You can now access them anywhere as:

MyLists.COUNTRIES

You can use a dependency injection:

public class Demo{
  List<String> list;

  public Demo(List<String> list){
   this.list = list;
  }
}

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