79

I have an ArrayList with values like "abcd#xyz" and "mnop#qrs". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:

String dsf[] = new String[al.size()];              
for(int i =0;i<al.size();i++){
  dsf[i] = al.get(i);
}

But it failed saying "Ljava.lang.String;@57ba57ba"

4
  • 2
    POst the definition of your ArrayList and the complete error message Commented Mar 29, 2012 at 16:18
  • 7
    What do you mean by "it failed saying ..."? That looks like the result of printing dsf.toString()...
    – Jon Skeet
    Commented Mar 29, 2012 at 16:19
  • Do you want an array of arrays of Strings, i.e. a 2 dimensional array?
    – Adam
    Commented Mar 29, 2012 at 16:20
  • 2
    possible duplicate of Convert ArrayList containing Strings to an array of Strings in Java?
    – Nateowami
    Commented Dec 4, 2014 at 9:45

12 Answers 12

127

You don't need to reinvent the wheel, here's the toArray() method:

String []dsf = new String[al.size()];
al.toArray(dsf);
2
  • ArrayList<String> a1 = new ArrayList<String>(); for (Entry<String, String> entry : outmap.entrySet()) { if(entry.getKey().indexOf("Data") != -1){ exports.add(entry.getValue()); } }
    – Shruthi
    Commented Mar 29, 2012 at 16:24
  • There's also this form 'docs.oracle.com/javase/1.5.0/docs/api/java/util/…' for where you want to provide a specificly typed array. Commented Mar 29, 2012 at 16:29
64
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])
10
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki"); 
String names[]=list.toArray(new String[0]);

if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.

2
  • 1
    I think new String[0] redundant because you always have the list. So you can determine the size. Commented Mar 3, 2017 at 3:30
  • 2
    You can/should replace new String[0] with new String[list.size()] Commented May 16, 2017 at 19:53
2
import java.util.*;
public class arrayList {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        ArrayList<String > x=new ArrayList<>();
        //inserting element
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
         //to show element
         System.out.println(x);
        //converting arraylist to stringarray
         String[]a=x.toArray(new String[x.size()]);
          for(String s:a)
           System.out.print(s+" ");
  }

}
3
  • 1
    This doesn't do the requested split.
    – rghome
    Commented Jan 12, 2016 at 12:36
  • provide description for an answer if you want others to understand and maybe upvote it
    – insomniac
    Commented Jan 12, 2016 at 13:55
  • This approach is the same as the one in this answer posted a few years earlier. Commented Nov 16, 2017 at 9:37
2
String[] values = new String[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            values[i] = arrayList.get(i).type;
        }
1
  • Here arrayList.get(i).type is a one of the value in the arrayList. You can get it anyway.
    – Anand
    Commented Jun 8, 2016 at 10:33
1

What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29

Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:

for(String str : dsf){
   System.out.println(str);
}

What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.

1
package com.v4common.shared.beans.audittrail;

import java.util.ArrayList;
import java.util.List;

public class test1 {
    public static void main(String arg[]){
        List<String> list = new ArrayList<String>();
        list.add("abcd#xyz");
        list.add("mnop#qrs");

        Object[] s = list.toArray();
        String[] s1= new String[list.size()];
        String[] s2= new String[list.size()];

        for(int i=0;i<s.length;i++){
            if(s[i] instanceof String){
                String temp = (String)s[i];
                if(temp.contains("#")){
                    String[] tempString = temp.split("#");
                    for(int j=0;j<tempString.length;j++) {
                        s1[i] = tempString[0];
                        s2[i] = tempString[1];
                    }

                }
            }   
        }
        System.out.println(s1.length);
        System.out.println(s2.length);
        System.out.println(s1[0]);
        System.out.println(s1[1]);
    }
}
1

Here is the solution for you given scenario -

List<String>ls = new ArrayList<String>();
    ls.add("dfsa#FSDfsd");
    ls.add("dfsdaor#ooiui");
    String[] firstArray = new String[ls.size()];    
 firstArray =ls.toArray(firstArray);
String[] secondArray = new String[ls.size()];
for(int i=0;i<ls.size();i++){
secondArray[i]=firstArray[i].split("#")[0];
firstArray[i]=firstArray[i].split("#")[1];
} 
1

This is the right answer you want and this solution i have run my self on netbeans

ArrayList a=new ArrayList();
a.add(1);
a.add(3);
a.add(4);
a.add(5);
a.add(8);
a.add(12);

int b[]= new int [6];
        Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
        m=(Integer[]) a.toArray(m);
for(int i=0;i<a.size();i++)
{
    b[i]=m[i]; 
    System.out.println(b[i]);
}   
    System.out.println(a.size());
1
  • 1
    How is your answer better when the existing one and now only worse due to the use of raw-types?
    – Tom
    Commented Aug 26, 2017 at 15:19
1

NameOfArray.toArray(new String[0])

This will convert ArrayList to Array in java

0

This can be done using stream:

List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
    List<String[]> objects = stringList.stream()
                                       .map(s -> s.split("#"))
                                       .collect(Collectors.toList());

The return value would be arrays of split string. This avoids converting the arraylist to an array and performing the operation.

0
// A Java program to convert an ArrayList to arr[]
import java.io.*;
import java.util.List;
import java.util.ArrayList;

class Main {
     public static void main(String[] args)
    {
        List<Integer> al = new ArrayList<Integer>();
        al.add(10);
        al.add(20);
        al.add(30);
        al.add(40);

        Integer[] arr = new Integer[al.size()];
        arr = al.toArray(arr);

        for (Integer x : arr)
            System.out.print(x + " ");
     }
 }
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jul 15, 2022 at 12:42

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.