If you just want to have one list of words, you should definitely use a Singleton as a static member of your class.
This member should have a List and be created only once.
That's why the constructor should be private.
It should look like this
import java.util.Arrays;
import java.util.List;
public final class Vocabulary{
//The final in the class name is there so you can't heritate from this class
private static Vocabulary INSTANCE = null;
private List<String> words;
//Private so you can't create another instance of it, you need to use static method
private Vocabulary() {
this.words = Arrays.asList("hello", "stack", "heap");
}
//In case you want to implemente other public function
public static Vocabulary getInstance(){
if(INSTANCE == null){
INSTANCE = new Vocabulary();
}
return INSTANCE;
}
//If you want to choose a word by its number
public static String getWord(int i){
return Vocabulary.getVocabulary().get(i);
}
//Used in getVocabulary, getter of the List
private List<String> getWords(){
return this.words;
}
// Return the whole List of words
public static List<String> getVocabulary(){
return Vocabulary.getInstance().getWords();
}
// Here your go
public static String getRandomWord(){
return Vocabulary.getWord((int)(Math.random() * Vocabulary.getVocabulary().size()));
}
}
And then you can just use it properly :
public static void main(String[] args) {
System.out.println(Vocabulary.getRandomWord());
}
Singleton is a well known design pattern and this is a pretty clean way to do it, hope it helps !