Search code examples
javaarraysstringcreationseries

Java - Creating an array from a series of strings


this might be a beginners question, but I am only just learning to program using java :)

I have a program that depends on plugins for it's information. When the program loads, it loads all of the plugins alongside it. I would like to make a String array filled with the contents of a String from these plugins.

All plugins have the string getWikiName, but all plugins have different values for the string. When this program starts up, I need to combine all of these values into an array called wikiNameArray[] in an orderly fashion.

Plugin A: getWikiName = "String1";
Plugin B: getWikiName = "String2";

End Result: wikiNameArray[] = {"String1","String2"}

-edit-

Here is some new code that I found that might help.

getWikiName.toArray(wikiNameArray)

But does this add the string to the next free index in the array instead of just making the array equal to getWikiName?


Solution

  • If you know the size beforehand you can create an array and fill each cell directly:

    String[] wikiNameArray = new String[size];
    for (int i = 0; i < size; i++) {
        wikiNameArray[i] = getWikiName();
    }
    

    If you don't know the size use a List and convert it when it contains all strings

    List<String> list = new ArrayList<String>();
    for (Wiki wiki : wikis) {
        list.add(wiki.getWikiName());
    }
    String[] wikiNameArray= list.toArray(new String[list.size()]);