Conversion between a Java collection and an array

Source: Internet
Author: User

Java conversions between collections and arrays

@author Ixenos

Array to collection arrays.aslist (T ... a)

The first conclusion : Using Arrays.aslist (T ... a) to convert an array to a collection

(T...A) is a variable parameter, as (t[] a) can be

<T> list<t> aslist(T ... a)

Returns a fixed-size list supported by the specified array, which is a pure array in the form of a list, just a view of the original array (changes to the returned list are "directly written" to the array.) )

The returned list is serializable and implements the Randomaccess

This method also provides a convenient way to create a fixed-length list (which is a list) that is initialized to contain multiple elements:

List<string> stooges = arrays.aslist ("Larry", "Moe", "Curly");

Why is it a fixed size? Not "ArrayList"?

Because this is not the "ArrayList" you imagined, and there is no commitment to ArrayList, just return an interface type list!

SOURCE Analysis:

First look at the Aslist method:

 Public static <T> list<t> aslist (T ... a) {2     returnnew arraylist<> (a); 9 ·

It was suddenly discovered that the Aslist method originally called the constructor of the private static inner class ArrayList of the arrays class (rather than the ArrayList in the collection frame):

Private Final e[] A; 1 ArrayList (e[] array) {2     a = objects.requirenonnull (array); 9 ·

(Note: This class also inherits the Abstractlist<e> interface, similar to the ArrayList structure of the tool class (all maintaining an array), but the internal principle is different, it is just a list view of the array. Below is the source code)

1Private Static classArraylist<e>extendsAbstractlist<e> 2Implementsrandomaccess, Java.io.Serializable3     { 4Private Static Final LongSerialversionuid = -2764017481108945198l; 5Private Finale[] A;6 7ArrayList (e[] array) {8 A =objects.requirenonnull (array);9         }1011@Override12 Public intsize () {13returna.length;14         }1516@Override17 Publicobject[] ToArray () {18returnA.clone ();19         }2021@Override@SuppressWarnings ("Unchecked")23 Public<T>t[] ToArray (t[] a) {24intSize =size ();25if(A.length <size)26returnArrays.copyof ( This. A, size,(CLASS&LT;?extendsT[]>) A.getclass ());System.arraycopy ( This. A, 0, a, 0, size);29if(A.length >size)A[size] =NULL;31returnA;32         }3334@Override35 PublicE Get (intindex) {36returnA[index];37         }3839@Override40 PublicE Set (intindex, E Element) {E OldValue =A[index];A[index] =element;43returnOldValue;44         }4546@Override47 Public intindexOf (Object o) {E[] A = This. A;49if(O = =NULL) {50 for(inti = 0; i < a.length; i++)51if(A[i] = =NULL)52returni;53}Else {54 for(inti = 0; i < a.length; i++)55if(O.equals (A[i]))56returni;57             }58return-1;59         }6061@Override62 Public Booleancontains (Object o) {63returnIndexOf (o)! =-1;64         }6566@Override67 PublicSpliterator<e>Spliterator () {68returnSpliterators.spliterator (A, spliterator.ordered);69         }7071@Override72 Public voidForEach (consumer<?SuperE>action) {73Objects.requirenonnull (action);74 for(E e:a) {75action.accept (e);76             }77         }7879@Override80 Public voidReplaceAll (unaryoperator<e>operator) {81objects.requirenonnull (operator);E[] A = This. A;83 for(inti = 0; i < a.length; i++) {A[i] =operator.apply (A[i]);85             }86         }8788@Override89 Public voidSort (comparator<?SuperE>c) {90Arrays.sort (A, c);91         }92}
View Code

From this inner class to see the returned list as an array, you can not add and delete elements, can only be replaced and traversed without altering the structure of the operation

The Requirenonnull method in the constructor method is a non-null check (from the Objects Tool Class):

 Public static <T> t requirenonnull (t obj) {2     ifnull)3     Throw  New  nullpointerexception (); 4     return  obj; 5}

Visible, did not do any processing, just actually passed a generic array to reference A, indicating that the internal data structure is an array

Set-to- go array interface Method ToArray directly with

collection<e> interface of ToArray () and the ToArray (t[] a) :

1.object[] ToArray ()

Returns an array that contains all the elements in this collection, but is of type Object, and an unwarranted downward transformation is illegal, so even type conversions are not possible;

If collection makes certain assurances about the order of elements returned by its iterators (such as the comparator parameter), then this method must return the elements in the same order;

The returned array will be "safe," because this collection does not maintain any references to the returned array, which is not the view of the array, and the caller can arbitrarily modify the returned array

  In a word , generally do not use this good, type is flawed ...

2.<t> t[] ToArray (t[] a)

The run- time type of the returned array is the same as the run-time type of the specified array, so it is possible to pass in a specified type array;

  if the specified array can hold the Collection , the return contains this Collection element, otherwise a run-time type with the specified array is assigned and this Collection a new array of sizes ;

Therefore, you can directly pass in new T[0], allowing the method to automatically assign an array of type T corresponding to the collection size

If the specified array can hold collection, and there is space left (that is, the elements of the array are more than the elements of collection), then the element immediately below the collection in the array is set to Null( only if the caller knows that this collection does not contain any null elements

To determine the length of the collection with this method. )

This method allows precise control of the run-time type of the output array and, in some cases, can be used to save allocation overhead;

  In a word , an array of formal parameters is a container, which is sufficient (null), not enough to build a new one (the same as the run-time type and the formal parameter)

3. conclusion : Using the method ToArray (t[] a) to convert the set into an array

Parameter (t[] a) to specify the run-time type

Conversion between a Java collection and an array

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.