I am developing a java program for class, and I have some restrictions that are killing me. I have to read a file and save its words on a list, and then keep that list so I can take words out of it.
I have to read the file and select n words out of the list, and return those words, not the whole list. My question is: is there some way of creating the complete list as global or extern, so every method can access to it, with no need to be a parameter?? I need to be modifying the complete list, removing the words I am needing, and then using it again in other methods.
Thank you :)
You can make a member variable in a class public
and static
, and that way you can access it from anywhere:
public class One {
public static List<String> names = new ArrayList<>();
}
public class Two {
public void addName(String name) {
One.names.add(name);
}
}
public class Three {
public void printTheNames() {
System.out.println(One.names);
}
}
However...
These restrictions (like no way to create true global variables) are there for a good reason, and not because Java is lacking features. If you have trouble with these restrictions, then that's a sign you are trying to do things the wrong way - it means the design of your program has problems.
Almost always, global variables are bad.