Fearghal
Fearghal

Reputation: 11407

Extract String arrays from List

Developing a Java Android App but this is a straight up Java question i think.

I have List declared as follows;

List list= new ArrayList<String[]>();

I want to extract each String [] in a loop;

for(int i=0; i < list.size(); i++) {
   //get each String[]
   String[] teamDetails = (String[])list.get(i);
}

This errors, I am guessing it just doesn't like me casting the String[] like this.

Can anyone suggest a way to extract the String[] from my List?

Upvotes: 0

Views: 2639

Answers (5)

Raj Tandel
Raj Tandel

Reputation: 19

First of all you need to change declaration from List list= new ArrayList<String[]>(); to List<String[]> list = new ArrayList();

After that you can do something like

String[] temp =  new String[list.size];

for(int i=0;i<list.size();i++)`
{
temp[i] = list.get(i);
}

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65813

Use a List<String[]> and you can use the more up-to-date looping construct:

    List<String[]> list = new ArrayList<String[]>();

    //I want to extract each String[] in a loop;
    for ( String[] teamDetails : list) {

    }

    // To extract a specific one.
    String[] third = list.get(2);

Upvotes: 7

PKuhn
PKuhn

Reputation: 1360

Try declaring the list this way

List<String[]> list = new ArrayList<>();

for(int i = 0; i < list.size(); i++) {
    //get each String[]
    String[] teamDetails = list.get(i);
}

Moreover the call of your size function was wrong you need to add the brackets

Upvotes: 1

Manoj Kumar
Manoj Kumar

Reputation: 757

In for loop change list.size to list.size()

And it works fine Check this https://ideone.com/jyVd0x

Upvotes: 0

Androider
Androider

Reputation: 3873

    /*ArrayList to Array Conversion */
            String array[] = new String[arrlist.size()];              
            for(int j =0;j<arrlist.size();j++){
              array[j] = arrlist.get(j);
            }

//OR
/*ArrayList to Array Conversion */
        String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);

Upvotes: 0

Related Questions