简体   繁体   中英

How to add to ArrayList String that already declared

I have a class in which i declare many words as class variables. And there is a method to choose a random word from those class words. How can i implement getRandomWord properly?

public class Vocabulary
{
   int numOfWords = 2;

   final static word1 = "hello";
   final static word2 = "stack";
   ...

    public String getRandomWord()
   {
        int random = (int)(Math.random() * numOfWords + 1);
        return word + random;
   }
}

I tried to add those words to an ArrayList first and then return the index but i cant understand how to add those words that are already declared in the class to the ArrayList.

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 !

Make array like this:

String[] strs = { "hello","stack"};

Then add then to List<String> .

  List<String> list = Arrays.asList( strs );

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