简体   繁体   English

在java中将ArrayList转换为Array

[英]Converting ArrayList to Array in java

I have an ArrayList with values like "abcd#xyz" and "mnop#qrs".我有一个 ArrayList,其值如“abcd#xyz”和“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.我想把它转换成一个数组,然后用 # 作为分隔符将它拆分,并在一个数组中有 abcd,mnop,在另一个数组中有 xyz,qrs。 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"但它没有说“Ljava.lang.String;@57ba57ba”

You don't need to reinvent the wheel, here 's the toArray() method:你不需要重新发明轮子, 这里toArray()方法:

String []dsf = new String[al.size()];
al.toArray(dsf);
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.如果你看到最后一行(new String[0]),你不必给出大小,有时我们不知道列表的长度,所以从给它作为 0 开始,构造数组将调整大小。

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

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

This is the right answer you want and this solution i have run my self on netbeans这是您想要的正确答案,我已经在 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());

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.它为您提供了一个有效的 String 对象数组。 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就像在另一个答案中提到的那样,使用可用于 ArrayList 对象的 toArray() 方法更容易=> 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.如果您正确地迭代您的 dsf 数组并单独打印每个元素,您将获得有效的输出。 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.您可能尝试做的是一次打印完整的 Array 对象,因为这会给出一个对象内存地址,就像您在问题中得到的那样。 If you see that kind of output you need to provide a toString() method for the object you're printing.如果您看到这种输出,您需要为您正在打印的对象提供一个 toString() 方法。

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

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

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.这避免了将 arraylist 转换为数组并执行操作。

We can convert ararylist to array using 3 mrthod我们可以使用 3 mrthod 将 ararylist 转换为数组

  1. public Object[] toArray() - it will return array of object public Object[] toArray() - 它将返回对象数组

    Object[] array = list.toArray(); Object[] 数组 = list.toArray();

  2. public T[] toArray(T[] a) - In this way we will create array and toArray Take it as argument then return it public T[] toArray(T[] a) - 这样我们将创建数组和 toArray 将它作为参数然后返回它

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

    Iterate ararylist and one by one add element in array.迭代 ararylist 并在数组中一一添加元素。

For more details for these method Visit Java Vogue有关这些方法的更多详细信息,请访问Java Vogue

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 public T[] toArray(T[] a) - 在这个方法中,我们创建一个大小为arraylist的数组并将其作为参数传递,它将返回arraylist元素的数组

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

    arr = list.toArray(arr);

NameOfArray.toArray(new String[0])

这将在java中将ArrayList转换为Array

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM