How to add to ArrayList String that already declaredStatic Initialization BlocksSelect random Java variable? Is this possibleWhat is the difference between String and string in C#?Create ArrayList from arrayHow do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Does Python have a string 'contains' substring method?How do I convert a String to an int in Java?Why is char[] preferred over String for passwords?

Is it possible to create light that imparts a greater proportion of its energy as momentum rather than heat?

Alternative to sending password over mail?

Why doesn't using multiple commands with a || or && conditional work?

I'm flying to France today and my passport expires in less than 2 months

What killed these X2 caps?

How can saying a song's name be a copyright violation?

How do conventional missiles fly?

Is "remove commented out code" correct English?

Why do bosons tend to occupy the same state?

Why is the 'in' operator throwing an error with a string literal instead of logging false?

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Can one be a co-translator of a book, if he does not know the language that the book is translated into?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Would Slavery Reparations be considered Bills of Attainder and hence Illegal?

SSH "lag" in LAN on some machines, mixed distros

Forgetting the musical notes while performing in concert

Were any external disk drives stacked vertically?

Has there ever been an airliner design involving reducing generator load by installing solar panels?

Why are electrically insulating heatsinks so rare? Is it just cost?

Stopping power of mountain vs road bike

What is a clear way to write a bar that has an extra beat?

Western buddy movie with a supernatural twist where a woman turns into an eagle at the end

How to prevent "they're falling in love" trope

Is it legal for company to use my work email to pretend I still work there?



How to add to ArrayList String that already declared


Static Initialization BlocksSelect random Java variable? Is this possibleWhat is the difference between String and string in C#?Create ArrayList from arrayHow do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Does Python have a string 'contains' substring method?How do I convert a String to an int in Java?Why is char[] preferred over String for passwords?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















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.










share|improve this question



















  • 1





    Create a static List<String> words and there store your words. You can add them in static section manually

    – Michał Ziober
    Mar 8 at 0:38












  • How can i store the words in a loop? Or i have to store them manually?

    – Albert Leibnitz
    Mar 8 at 0:39











  • See static section questions stackoverflow.com/questions/2420389/…

    – Michał Ziober
    Mar 8 at 0:42











  • Possible duplicate of Select random Java variable? Is this possible

    – Tom
    Mar 8 at 0:45











  • To extend what @MichałZiober said: that's how you can get a random element from a list: Randomly select an item from a list

    – Tom
    Mar 8 at 0:46

















0















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.










share|improve this question



















  • 1





    Create a static List<String> words and there store your words. You can add them in static section manually

    – Michał Ziober
    Mar 8 at 0:38












  • How can i store the words in a loop? Or i have to store them manually?

    – Albert Leibnitz
    Mar 8 at 0:39











  • See static section questions stackoverflow.com/questions/2420389/…

    – Michał Ziober
    Mar 8 at 0:42











  • Possible duplicate of Select random Java variable? Is this possible

    – Tom
    Mar 8 at 0:45











  • To extend what @MichałZiober said: that's how you can get a random element from a list: Randomly select an item from a list

    – Tom
    Mar 8 at 0:46













0












0








0








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.










share|improve this question
















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.







java string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 0:38







Albert Leibnitz

















asked Mar 8 at 0:35









Albert LeibnitzAlbert Leibnitz

195




195







  • 1





    Create a static List<String> words and there store your words. You can add them in static section manually

    – Michał Ziober
    Mar 8 at 0:38












  • How can i store the words in a loop? Or i have to store them manually?

    – Albert Leibnitz
    Mar 8 at 0:39











  • See static section questions stackoverflow.com/questions/2420389/…

    – Michał Ziober
    Mar 8 at 0:42











  • Possible duplicate of Select random Java variable? Is this possible

    – Tom
    Mar 8 at 0:45











  • To extend what @MichałZiober said: that's how you can get a random element from a list: Randomly select an item from a list

    – Tom
    Mar 8 at 0:46












  • 1





    Create a static List<String> words and there store your words. You can add them in static section manually

    – Michał Ziober
    Mar 8 at 0:38












  • How can i store the words in a loop? Or i have to store them manually?

    – Albert Leibnitz
    Mar 8 at 0:39











  • See static section questions stackoverflow.com/questions/2420389/…

    – Michał Ziober
    Mar 8 at 0:42











  • Possible duplicate of Select random Java variable? Is this possible

    – Tom
    Mar 8 at 0:45











  • To extend what @MichałZiober said: that's how you can get a random element from a list: Randomly select an item from a list

    – Tom
    Mar 8 at 0:46







1




1





Create a static List<String> words and there store your words. You can add them in static section manually

– Michał Ziober
Mar 8 at 0:38






Create a static List<String> words and there store your words. You can add them in static section manually

– Michał Ziober
Mar 8 at 0:38














How can i store the words in a loop? Or i have to store them manually?

– Albert Leibnitz
Mar 8 at 0:39





How can i store the words in a loop? Or i have to store them manually?

– Albert Leibnitz
Mar 8 at 0:39













See static section questions stackoverflow.com/questions/2420389/…

– Michał Ziober
Mar 8 at 0:42





See static section questions stackoverflow.com/questions/2420389/…

– Michał Ziober
Mar 8 at 0:42













Possible duplicate of Select random Java variable? Is this possible

– Tom
Mar 8 at 0:45





Possible duplicate of Select random Java variable? Is this possible

– Tom
Mar 8 at 0:45













To extend what @MichałZiober said: that's how you can get a random element from a list: Randomly select an item from a list

– Tom
Mar 8 at 0:46





To extend what @MichałZiober said: that's how you can get a random element from a list: Randomly select an item from a list

– Tom
Mar 8 at 0:46












2 Answers
2






active

oldest

votes


















0














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 !






share|improve this answer






























    0














    Make array like this:



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


    Then add then to List<String>.



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





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55055060%2fhow-to-add-to-arraylist-string-that-already-declared%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      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 !






      share|improve this answer



























        0














        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 !






        share|improve this answer

























          0












          0








          0







          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 !






          share|improve this answer













          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 !







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 2:16









          NohTowNohTow

          63




          63























              0














              Make array like this:



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


              Then add then to List<String>.



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





              share|improve this answer





























                0














                Make array like this:



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


                Then add then to List<String>.



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





                share|improve this answer



























                  0












                  0








                  0







                  Make array like this:



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


                  Then add then to List<String>.



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





                  share|improve this answer















                  Make array like this:



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


                  Then add then to List<String>.



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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 8 at 2:32

























                  answered Mar 8 at 2:24









                  Common ManCommon Man

                  2,24031431




                  2,24031431



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55055060%2fhow-to-add-to-arraylist-string-that-already-declared%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                      Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                      Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved