Ebad Saghar
Ebad Saghar

Reputation: 1127

How to get an element from a String Array, if the String array itself is an element of an ArrayList?

Let me give you an example;

String[] one = {"one", "two"};
String[] two = {"bob", "lol", "hi"};
List<String[]> list = new ArrayList<String[]>();
list.add(one);
list.add(two);

Now, I want to get the 2nd string array (which is 'two') in list. I do this by:

list.get(2);

But, say if I wanted to get the 2nd element in the two String array in List ( Basically I want to get the string "lol" from list->two->lol).

Is this how you do it:

list.get(2).get(2) 

Upvotes: 0

Views: 49

Answers (2)

Shriram
Shriram

Reputation: 4411

Array starts with index 0. so you have to use list.get(i)[1]

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

Indices in Java (and in most programming languages) starts with 0, so if you want to access to the second element you must use the index 1:

list.get(0)[1];

Note that

list.get(0)

will return the first String[] array, and to access to an element of an array you have to use the syntax:

someArray[index]

Upvotes: 3

Related Questions