-3

So lets say I want to make an array of nine country names. I have the code to create the array:

String[] countryName = new String[9];

Lets say I wanted to add nine unique country names to this array. I could do something like this:

countryName[0] = "Mexico";
countryName[1] = "United States";

and so on. But is there a way I could add all of the names at once? Maybe something like an add() statement?

jknudsen99
  • 121
  • 1
  • 1
  • 3
  • 1
    possible duplicate of [How to declare an array in Java?](http://stackoverflow.com/questions/1200621/how-to-declare-an-array-in-java) – Smutje Jul 03 '14 at 10:10
  • 5
    You can just use `String[] countryName = { "Mexico", "United States", ... };`. I would strongly advise reading a good Java book for this sort of thing though - it's a much more efficient way of learning the basics of a language than asking specific questions on Stack Overflow. – Jon Skeet Jul 03 '14 at 10:11

4 Answers4

9

you can initialize the array with:

String[] countryName = new String[]{"Mexico", "Italy", "Spain"};
Michel Foucault
  • 1,597
  • 3
  • 22
  • 39
1

You can write simple utility method using varargs

static void addAll(String[] arr, String ... elements)
{
   if (elements != null)
   {
      System.arraycopy(elements, 0, arr, 0, elements.length);
   }
}  

Usage

addAll(countryName, "Mexico", "US", "Ukraine");
Ilya
  • 27,538
  • 18
  • 104
  • 148
0

Enlist all contries in String and use split

   String str="Country1,Country2,Country3";
   String array[]=str.split(",");//You even don't need to initialize array

Use delimeter carefully to avoid extra spaces.


NOTE: As this is one of the ways to add values to array but still I suggest you to go for Michel Foucault's answer as split will have more overhead than direct initialization.

ΔȺȾΔ
  • 21,571
  • 10
  • 52
  • 80
0

Use an ArrayList this has the Add method.

ArrayList<String> countryName = new ArrayList<String>();
countryName.add("Mexico");
countryName.add("United States");
countryName.add("Dominican Republic");
countryName.add("...");
Holt
  • 32,271
  • 6
  • 74
  • 116
DannyFeliz
  • 642
  • 7
  • 16