Fill a array with List data

前端 未结 5 1873
暖寄归人
暖寄归人 2020-12-12 02:43

How can I fill a array with the data provided by one List?

For example, I have a List with Strings:

List l = new ArrayList();
l.add(\"a         


        
5条回答
  •  醉梦人生
    2020-12-12 03:14

    You can use the toArray(T[] a) method:

    String[] arr = list.toArray(new String[0]);
    

    Or alternately:

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

    The difference between the two is that the latter may not need to allocate a new array.


    Effective Java 2nd Edition: Item 23: Don't use raw types in new code.

    JLS 4.8 Raw Types

    The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.


    Don't make a habit of naming an identifier l. It looks an awful lot like 1.

提交回复
热议问题