Convert ArrayList to String array in Android

前端 未结 7 1170
终归单人心
终归单人心 2020-12-08 00:56

I have a ArrayList that contains values in the form [ann,john]. I want to convert this ArrayList into a String array in the form {\"ann\",\"john\"}.

How should I do

相关标签:
7条回答
  • 2020-12-08 01:20

    You can try this code

    String[] stringA = new String[stringArrayList.size()];
    stringArrayList.toArray(stringA)
    System.out.println(stringA[0]);
    
    0 讨论(0)
  • 2020-12-08 01:24

    Use the method "toArray()"

    ArrayList<String>  mStringList= new ArrayList<String>();
    mStringList.add("ann");
    mStringList.add("john");
    Object[] mStringArray = mStringList.toArray();
    
    for(int i = 0; i < mStringArray.length ; i++){
        Log.d("string is",(String)mStringArray[i]);
    }
    

    or you can do it like this: (mentioned in other answers)

    ArrayList<String>  mStringList= new ArrayList<String>();
    mStringList.add("ann");
    mStringList.add("john");
    String[] mStringArray = new String[mStringList.size()];
    mStringArray = mStringList.toArray(mStringArray);
    
    for(int i = 0; i < mStringArray.length ; i++){
        Log.d("string is",(String)mStringArray[i]);
    }
    

    http://developer.android.com/reference/java/util/ArrayList.html#toArray()

    0 讨论(0)
  • 2020-12-08 01:30
    String[] array = new String[items2.size()];
    items2.toArray(array);
    
    0 讨论(0)
  • 2020-12-08 01:31

    You could make an array the same size as the ArrayList and then make an iterated for loop to index the items and insert them into the array.

    0 讨论(0)
  • 2020-12-08 01:35

    I know im very late to answer this. But it will help others, I was also stucked on this.

    Here is what i did to get it work.

    String[] namesArr = (String[]) names.toArray(new String[names.size()]);
    
    0 讨论(0)
  • 2020-12-08 01:35
    try this
    
    List<String> list = new ArrayList<String>();
    list.add("List1");
    list.add("List2");
    
    String[] listArr = new String[list.size()];
    listArr = list.toArray(listArr );
    
    for(String s : listArr )
        System.out.println(s);
    
    0 讨论(0)
提交回复
热议问题