Question

I need to put several strings into a java array for example.

"Dog","Cat","Lion","Giraffe"
"Car","Truck","Boat","RV"

each of the above would be 1 key in the array

array[0] = "Dog","Cat","Lion","Giraffe"
array[1] =  "Car","Truck","Boat","RV"

Not sure how to do this,or should I be using something other than an array,and how to get each individual element i.e array[0]"Lion"

Thanks

Was it helpful?

Solution

Declare the array like this:

String [][]array = { 
    { "Dog","Cat","Lion","Giraffe"}, 
    {"Car","Truck","Boat","RV"}
};

and use the items like this:

array[0][0]; // this would be "Dog"
array[1][0]; // this would be "Car"

OTHER TIPS

You can use a multidimensional array:

String[][] something =
    { 
        { "hello", "kitties" }, 
        {  "i", "am", "a", "pony" } 
    };

Well you can do it by declaring a map like so Map<String, MySweetObject> or create a List<String> and put each list into the array.

You need a jagged array, which is an array of arrays:

String [][]array  = { {"Dog","Cat","Lion","Giraffe"}, {"Car","Truck","Boat","RV"}};

You can then access the content as this:

array[0] // will be the String array {"Dog","Cat","Lion","Giraffe"}
array[1] // will be the String array {"Car","Truck","Boat","RV"}
array[0][2] // Lion
array[1][0] // Car
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top