Converting List to String[] in Java

后端 未结 6 1607
暖寄归人
暖寄归人 2020-12-25 10:52

How do I convert a list of String into an array? The following code returns an error.

public static void main(String[] args) {
    List strlist         


        
相关标签:
6条回答
  • 2020-12-25 11:02

    hope this can help someone out there:

    List list = ..;

    String [] stringArray = list.toArray(new String[list.size()]);

    great answer from here: https://stackoverflow.com/a/4042464/1547266

    0 讨论(0)
  • 2020-12-25 11:11

    String[] strarray = strlist.toArray(new String[0]);

    if u want List convert to string use StringUtils.join(slist, '\n');

    0 讨论(0)
  • 2020-12-25 11:13

    List.toArray() necessarily returns an array of Object. To get an array of String, you need to use the casting syntax:

    String[] strarray = strlist.toArray(new String[0]);
    

    See the javadoc for java.util.List for more.

    0 讨论(0)
  • 2020-12-25 11:18

    You want

    String[] strarray = strlist.toArray(new String[0]);
    

    See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer

    System.out.println(Arrays.toString(strarray));
    

    since that will print the actual elements.

    0 讨论(0)
  • 2020-12-25 11:18
    public static void main(String[] args) {
        List<String> strlist = new ArrayList<String>();
        strlist.add("sdfs1");
        strlist.add("sdfs2");
    
        String[] strarray = new String[strlist.size()]
        strlist.toArray(strarray );
    
        System.out.println(strarray);
    
    
    }
    
    0 讨论(0)
  • 2020-12-25 11:20

    I've designed and implemented Dollar for this kind of tasks:

    String[] strarray= $(strlist).toArray();
    
    0 讨论(0)
提交回复
热议问题