The practice of converting Java arrays to lists

Source: Internet
Author: User
Tags addall

Never thought, "Java Array conversion to list" unexpectedly have so many knowledge, shock and entrainment a little unbearable. About "Java Array conversion to list" is actually very basic knowledge, and there are a lot of people in the blog has been discussed, it is inevitable that I feel that writing such a discussion article how much is not necessary! On second thought, "Do not accumulate silicon step, not to become thousands of miles", so forced themselves again to do some deep-seated practice of the problem.

First, Create ArrayList from array

I was surprised at how enthusiastic the discussion of Create ArrayList from array was on StackOverflow:

    1. New ArrayList (Arrays.aslist (array))
    2. List List = arrays.aslist (array);
    3. Use Guava--lists.newarraylist (Astringarray);
    4. Collections.addall (ArrayList, array);
    5. for (Element E:array)--list.add (e);

From the inside can be extracted from the above five programs, about guava, because I do not know very well, so temporarily let go, then the remaining four kinds of situation, we will do in detail to do the practice.

①, New ArrayList (Arrays.aslist (array))

In fact, I think the first kind of solution is very concise and good.

String[] Array1 = {NewString ("1"),NewString ("2"),NewString ("3")};arraylist =NewArraylist<string> (Arrays.aslist (array1)); for(String s:arraylist) {System.out.print (S +",");}Try{Arraylist.add ("111"); for(String s:arraylist) {System.out.print (S +","); }}Catch(Exception e) {System.out.print (e);}Try{array[1] ="QW"; for(String s:arraylist) {System.out.print (S +","); }}Catch(Exception e) {System.out.print (e);} System.out.println (); System.out.println ("----------New Arraylist<string> (Arrays.aslist (array1))---------------");

The output reads as follows:

1, 2, 3, 1, 2, 3, 111, 1, 2, 3, 111,
———-New ArrayList (Arrays.aslist (array1)) —————

However, after reading the discussion on StackOverflow, I feel that this kind of solution has the biggest disadvantage indeed!

You may create and fill the lists!

OK, this process will produce two lists, really let a person to break the heart! Note, however, that there is a "new ArrayList" between this method and the second method, so why new one? Take a look at the introduction of the second Method!

②, List list = Arrays.aslist (array)

From the Java API, we can see that

Aslist
public static list Aslist (T ... a) returns a list of fixed sizes supported by the specified array. (Changes to the returned list are "directly written" 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<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

Parameters:
A-an array of supported lists.
Return:
Specifies the list view of the array.

There are two drawbacks to this approach:

    1. The list length is fixed, which means that the add element cannot be made.
    2. Changes to the return list are "directly written" to the array.

Let's look at an example:

String[] Array = {NewString ("1"),NewString ("2"),NewString ("3") }; list<string> arrayList = arrays.aslist (array); for(String s:arraylist) {System.out.print (S +",");}Try{Arraylist.add ("111"); for(String s:arraylist) {System.out.print (S +","); }}Catch(Exception e) {System.out.print (e);}Try{Arraylist.set (1,"QW"); for(String S:array) {System.out.print (S +","); }}Catch(Exception e) {System.out.print (e);} System.out.println (); System.out.println ("----------arrays.aslist---------------");

The output results are as follows:

1, 2, 3, Java.lang.UnsupportedOperationException1, QW, 3,
———-arrays.aslist —————

From the results, it can be proved that:

This would work fine. But some caveats:

  1. The list returned from Aslist has a fixed size. So, if you want to is able to add or remove elements from the returned list in your code, you'll need to wrap it in a new ArrayList. Otherwise you'll get an unsupportedoperationexception.
  2. The list returned from Aslist () are backed by the original array. If you modify the original array, the list is modified as well. This could be surprising.

So the "array conversion to List" approach is limited, limiting the use of the list after conversion!

Then go back to the first method "New ArrayList (Arrays.aslist (Array)"), using new ArrayList obviously circumvent the above two limitations, but also create two list, so the above two methods, although the code is concise enough, But the disadvantage is also many, that is to say these two methods somewhat "Sequela".

④, Collections.addall (ArrayList, array);

Skip guava and let's see "Collections.addall (ArrayList, Array)".

String[] Array2 = {NewString ("1"),NewString ("2"),NewString ("3")};arraylist =NewArraylist<string> (); Collections.addall (ArrayList, array2); for(String s:arraylist) {System.out.print (S +",");}Try{Arraylist.add ("111"); for(String s:arraylist) {System.out.print (S +","); }}Catch(Exception e) {System.out.print (e);}Try{array[1] ="QW"; for(String s:arraylist) {System.out.print (S +","); }}Catch(Exception e) {System.out.print (e);} System.out.println (); System.out.println ("-------------collections.addall (arrayList, array2)------------");

For the fourth method, I think it is good, the code is concise enough, and there is no redundant "sequela", so recommend this practice!

In addition, the following explanations can be found through the API:

public static Boolean AddAll (collection< super t> c,t ... elements)

Adds all the specified elements to the specified collection. You can specify the elements you want to add individually, or specify them as an array. The behavior of this handy method is the same as C.addall (Arrays.aslist (elements)), but in most implementations, this method can be much faster to run.

This method provides a convenient way to add a few elements to an existing collection when you specify the elements individually:
Collections.addall (Flavors, "Peaches ' N Plutonium", "Rocky racoon");

There's another way to do that.

new String("1"new String("2"new String("3"new ArrayList<String>();arrayList3.addAll(Arrays.asList(array3));

This is better than collections.addall!.

⑤, for (Element E:array)--list.add (e);

In fact, many times we neglect the most primitive writing, that is, the so-called

new ArrayList<String>();for (String s : array3) {    arrayList3.add(s);}

This kind of writing in my opinion, also enough concise, same no sequela, and running speed, I think, certainly not slow!

After summing up the above "Java Array conversion to list" method, really feel that the original basic knowledge is so deep, quickly learn it!

Thank you for reading "Silent Wang er Blog", if Wang ER's blog to bring you a hint of help or touched, I (that is, Wang II) will not be very honored.
If you happen to like it, you can leave a message or send it to me, which will be the strongest motivation for me to tinker with more excellent articles.

The practice of converting Java arrays to lists

Related Article

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.