[java] Converting ArrayList to Array in java

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"

This question is related to java arrays arraylist

The answer is


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

String []dsf = new String[al.size()];
al.toArray(dsf);

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.


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]);
    }
}

public T[] toArray(T[] a) - In this method we create a array with size of arraylist and pass it as argument and it will return array of element of arraylist

    String[] arr = new String[list.size()]; 

    arr = list.toArray(arr);

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+" ");
  }

}

List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])

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.


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());

String[] values = new String[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            values[i] = arrayList.get(i).type;
        }

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.


We can convert ararylist to array using 3 mrthod

  1. public Object[] toArray() - it will return array of object

    Object[] array = list.toArray();

  2. public T[] toArray(T[] a) - In this way we will create array and toArray Take it as argument then return it

       String[] arr = new String[list.size()]; 
        arr = list.toArray(arr);
    
  3. Public get() method;

    Iterate ararylist and one by one add element in array.

For more details for these method Visit Java Vogue


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];
} 

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable