List and Array transfer

Source: Internet
Author: User

1. List to array

Using the t[] List.toarray (t[] a) method in the API, cannot be used directly (t[]) List.toarray ()

Because arrays cannot be cast directly, for example

        Object[] objs={"123", "456"};        String[] Strings=(string[]) Objs;        System.out.println (Arrays.tostring (strings));
        list<string> list=New arraylist<>();        List.add ("abc");        List.add ("deg");        String[] Strings=(string[]) List.toarray ();        System.out.println (Arrays.tostring (strings));

This will cause classcastexception,

So it is not possible to use this method directly, ToArray (new t[size])must be used; The size here can be any number

        list<string> list=New arraylist<>();        List.add ("abc");        List.add ("deg");        List.add ("Teg");        string[] Strings  = (string[]) List.toarray (new string[1]);        System.out.println (Arrays.tostring (strings));

2. Array Goto List

Call the Aslist method of arrays.
Aslist
public static <T> list<t> aslist (T ... a) returns a list of fixed sizes supported by the specified array. (Changes to the returned list are "written straight" to the array.) This approach, together with Collection.toarray, serves as a bridge between an array-based API and an Collection-based API. The returned list is serializable and implements the randomaccess.
This method also provides a convenient way to create a fixed-length list that is initialized to contain multiple elements:

List stooges = arrays.aslist ("Larry", "Moe", "Curly");
Parameters:
A-an array of supported lists.
Return:
Specifies the list view of the array.
See also:
Collection.toarray ()

        string[] strings={"Hello", "World"};        List<String> list=arrays.aslist (strings);        System.out.println (List.tostring ());

[Hello, World]

  

List and Array transfer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.