Java source Code Analysis Arrays.aslist method detailed _java

Source: Internet
Author: User
Tags addall int size static class

Recently, the time to take the Java Arrays Tool class Aslist method to do the source code analysis, the online collation of relevant information, recorded down, hope can also help readers!

The Arrays tool class provides a method Aslist, using this method You can convert a variable-length parameter or array into a list.

The source code is as follows:

 /**
  * Returns a fixed-size list backed by the specified array. (Changes to
  * The returned list, "write through" to the array.) This is Acts
  * as bridge between array-based and Collection-based APIs, in
  * combination with {@link Collectio N#toarray}. The returned list is
  * Serializable and implements {@link randomaccess}.
  *
  * <p>this method also provides a convenient way to create a fixed-size
  * list initialized to contain sever Al elements:
  * <pre>
  *  list<string> stooges = arrays.aslist ("Larry", "Moe", "Curly");
  * </pre> * *
  @param a The array by which the list would be backed
  * @return A list view of the Specifi Ed Array
  *
 /@SafeVarargs public
 static <T> list<t> aslist (T ... a) {return
  new Arraylist<> (a);
 }
 

Problem found

Based on the description of the above method, let's start by writing a few examples:

/**
 * @author Wangmengjun
 *
 *
/public class Arrayexample {public
 
 static void Main (string[] args) { c6/>/** use variable length parameters
  /list<string> array1 = arrays.aslist ("Welcome", "to", "Java", "World");
  System.out.println (array1);
  
  /** uses the array
  /list<string> array2 = arrays.aslist (new string[] {"Welcome", "to", "Java", "World"});
  System.out.println (array2);
 }



Run the above program, output the following content.

[Welcome, to, Java, world]
[Welcome, to, Java, world]

On a whim, suddenly want to add a string "cool~~~" to the list created, walk one.

 /** use variable length parameters
  /list<string> array1 = arrays.aslist ("Welcome", "to", "Java", "World");
  Array1.add ("cool~~~");

As a result, a unsupportedoperationexception exception was encountered:

Exception in thread ' main ' java.lang.UnsupportedOperationException at
 java.util.AbstractList.add (Unknown Source) At
 Java.util.AbstractList.add (Unknown Source) at
 Test. Arrayexample.main (arrayexample.java:36)

Strangely, the new arraylist<> (a) generated list calls the Add method, unexpectedly encountering a problem.

Reason Lookup

So the question is, what the hell is going on? With doubt, go to check the arrays.aslist used in the ArrayList exactly what kind of?

The ArrayList class used by the original arrays Aslist method is an internally defined class, not a Java.util.ArrayList class.

The source code is as follows:

 /** * @serial include/private static class Arraylist<e> extends Abstractlist<e> implements Ra
    Ndomaccess, java.io.Serializable {private static final long serialversionuid = -2764017481108945198l;

    Private final e[] A;
      ArrayList (e[] array) {if (array==null) throw new NullPointerException ();
    A = array;
    public int size () {return a.length;
    Object[] ToArray () {return a.clone ();
      } public <T> t[] ToArray (t[] a) {int size = size (); if (A.length < size) return arrays.copyof (THIS.A, size, (class<? extends t[]>) A.GETCL
      Ass ());
      System.arraycopy (THIS.A, 0, a, 0, size);
      if (a.length > Size) a[size] = null;
    return A;
    Public E get (int index) {return a[index];
      Public e Set (int index, E element) {E oldValue = A[index];
      A[index] = element;
    return oldValue;public int indexOf (Object o) {if (o==null) {for (int i=0; i<a.length; i++) if (a[i]==n
      ULL) return i;
      else {for (int i=0; i<a.length; i++) if (O.equals (a[i)) return i;
    } return-1;
    Public Boolean contains (Object o) {return indexOf (o)!=-1;
 }
  }

From the implementation of the inner class ArrayList, it inherits the abstract class Java.util.abstractlist<e>, but does not rewrite the Add and remove methods , and does not give a specific implementation.

However, by default, the Java.util.AbstractList class throws a Unsupportedoperationexception exception directly in the Add, set, and remove methods. Abstractlist part of the source code is as follows:

Public abstract class Abstractlist<e> extends abstractcollection<e> implements list<e> {/** * Sol E constructor.
   (for invocation by subclass constructors, typically * implicit.) 
  * * Protected abstractlist () {} public E set (int index, E Element) {throw new unsupportedoperationexception (); }/** * {@inheritDoc} * * <p>this implementation always throws an * {@code unsupportedoperationexc
   Eption}.  * * @throws unsupportedoperationexception {@inheritDoc} * @throws classcastexception {@inheritDoc} * @throws nullpointerexception {@inheritDoc} * @throws illegalargumentexception {@inheritDoc} * @throws Indexoutofbound
  sexception {@inheritDoc} */public void Add (int index, E Element) {throw new unsupportedoperationexception (); }/** * {@inheritDoc} * * <p>this implementation always throws an * {@code unsupportedoperationexce
   Ption}. * * @throws Unsupportedoperationexception {@inheritDoc} * @throws indexoutofboundsexception {@inheritDoc} */public E remove (int index) {thro
  W new Unsupportedoperationexception ();

 }
}

It is precisely because the inner class arraylist of the Java.util.Arrays class does not override the Add and remove methods , so when we call its Add method, we actually call the Add method of the Abstractlist class. The result is to throw the unsupportedoperationexception exception directly.

Similarly, a unsupportedoperationexception exception is encountered when calling the Remove method, or by calling other methods associated with the Add, remove method (such as AddAll).

Examples of AddAll:

/**
 * @author Wangmengjun
 *
 *
/public class Arrayexample {public

  static void Main (string[] args) { c8/>/** use variable length parameters
    /list<string> array1 = arrays.aslist ("Welcome", "to", "Java", "World");
    Array1.addall (Arrays.aslist ("AAA", "BBB"));
  }



Exception in thread ' main ' java.lang.UnsupportedOperationException at
 java.util.AbstractList.add (Unknown Source At
 Java.util.AbstractList.add (Unknown source) at
 java.util.AbstractCollection.addAll (Unknown source) At
 Test. Arrayexample.main (arrayexample.java:36)
 

Example of Set:

/**
 * @author Wangmengjun
 *
 *
/public class Arrayexample {public

  static void Main (string[] args) { c7/>/** use variable length parameters
    /list<string> array1 = arrays.aslist ("Welcome", "to", "Java", "World");
    System.out.println (array1);
    
    Replace Java
    with Hello Array1.set (2, "Hello");
    System.out.println (array1);
  }



It is precisely because arrays's internal class ArrayList rewrite the set method that the above program works correctly and does not throw unsupportedoperationexception exceptions.

The results are as follows:

[Welcome, to, Java, world]
[Welcome, to, Hello, world]

Working with scenes

From the above example and the simple analysis, the Arrays tool class provides a method Aslist, which can be used to convert a variable length parameter or array into a list.

However, the resulting list is fixed in length, can be modified (for example, modifying elements in a location), and cannot perform operations that affect length (such as Add, remove, and so on). Throws a Unsupportedoperationexception exception.

Arrays.aslist is more suitable for those that already have array data or some elements, but need to quickly build a list, only for reading operations, without adding or deleting operations.

If you want to get a quick list of given based on the data from the group, a simpler way to do this is as follows:

Re-use the Java.util.ArrayList wrapper one layer.

/**
 * @author Wangmengjun
 *
 *
/public class Arrayexample {public

  static void Main (string[] args) { c6/>/** using variable-length parameters
    /list<string> array1 = new Arraylist<> (arrays.aslist ("Welcome", "to", "Java", "World") );
    System.out.println (array1);

    Array1.add ("cool~~~");
    System.out.println (array1);

  }



The results are as follows:

[Welcome, to, Java, world]
[Welcome, to, Java, World, cool~~~]

Thank you for reading, I hope to help you, thank you for your support for this site!

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.