如何添加到已经声明的ArrayList字符串

时间:2019-03-08 00:35:56

标签: java string

我有一个类,其中我将许多单词声明为类变量。并且有一种方法可以从这些类别词中选择一个随机词。如何正确实现getRandomWord?

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;
   }
}

我试图先将这些单词添加到ArrayList中,然后返回索引,但我不明白如何将已在类中声明的那些单词添加到ArrayList中。

2 个答案:

答案 0 :(得分:0)

如果只想列出一个单词,则绝对应该将Singleton用作类的静态成员。 该成员应具有一个列表,并且只能创建一次。 这就是为什么构造函数应该是私有的。 看起来应该是这样

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()));
  }
}

然后您可以正确使用它:

public static void main(String[] args) {
    System.out.println(Vocabulary.getRandomWord());
}

Singleton是一种众所周知的设计模式,这是一种非常干净的方法,希望对您有所帮助!

答案 1 :(得分:0)

使数组像这样:

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

然后将其添加到List<String>

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