Home Java javaTutorial Java source code analysis Arrays.asList method detailed explanation

Java source code analysis Arrays.asList method detailed explanation

Feb 04, 2017 am 10:11 AM

Recently, I took the time to analyze the source code of the asList method of the java Arrays tool class, compiled relevant information on the Internet, and recorded it. I hope it can also help readers!

The Arrays tool class provides a method asList, which can be used to 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 method acts
 * as bridge between array-based and collection-based APIs, in
 * combination with {@link Collection#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 several elements:
 * <pre class="brush:php;toolbar:false">
 *  List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
 * 
* * @param a the array by which the list will be backed * @return a list view of the specified array */ @SafeVarargs public static List asList(T... a) { return new ArrayList<>(a); }
Copy after login

Problem discovery

According to the description of the above method, let’s write a few examples first:

/**
 * @author wangmengjun
 *
 */
public class ArrayExample {
  
 public static void main(String[] args) {
   
  /**使用变长参数*/
  List<String> array1 = Arrays.asList("Welcome", "to","Java", "world");
  System.out.println(array1);
   
  /**使用数组*/
  List<String> array2 = Arrays.asList(new String[] {"Welcome", "to","Java", "world"});
  System.out.println(array2);
 }
 
}
Copy after login

Run the above program , output the following content.

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

On a whim, I suddenly want to add a string to the created list" Cool~~~", Go one.

/**使用变长参数*/
 List<String> array1 = Arrays.asList("Welcome", "to","Java", "world");
 array1.add("Cool~~~");
Copy after login

As a result, an UnsupportedOperationException 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)
Copy after login

Incredibly, the list generated by new ArrayList<>(a) encountered a problem when calling the add method.

Cause search

Then the question is, what happened? With questions in mind, let’s check out what the ArrayList used in Arrays.asList looks like?

It turns out that the ArrayList class used by the asList method of Arrays is an internally defined class, not the java.util.ArrayList class.

The source code is as follows:

/**
  * @serial include
  */
 private static class ArrayList<E> extends AbstractList<E>
   implements RandomAccess, 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;
   }
 
   public 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.getClass());
     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]==null)
           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;
   }
 }
Copy after login

It can be seen from the implementation of this internal class ArrayList that it inherits the abstract class java.util. AbstractList, but the add and remove methods are not rewritten and no specific implementation is given.

However, by default, the java.util.AbstractList class will directly throw UnsupportedOperationException in the add, set and remove methods. Part of the source code of AbstractList is as follows:

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
  /**
   * Sole 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 UnsupportedOperationException}.
   *
   * @throws UnsupportedOperationException {@inheritDoc}
   * @throws ClassCastException      {@inheritDoc}
   * @throws NullPointerException     {@inheritDoc}
   * @throws IllegalArgumentException   {@inheritDoc}
   * @throws IndexOutOfBoundsException   {@inheritDoc}
   */
  public void add(int index, E element) {
    throw new UnsupportedOperationException();
  }
 
  /**
   * {@inheritDoc}
   *
   * <p>This implementation always throws an
   * {@code UnsupportedOperationException}.
   *
   * @throws UnsupportedOperationException {@inheritDoc}
   * @throws IndexOutOfBoundsException   {@inheritDoc}
   */
  public E remove(int index) {
    throw new UnsupportedOperationException();
  }
}
Copy after login

It is precisely because the internal class ArrayList of the java.util.Arrays class does not override the add and remove methods, so when When we call its add method, we actually call the add method of the AbstractList class, and the result is that an UnsupportedOperationException is thrown directly.

Similarly, you will also encounter UnsupportedOperationException when calling the remove method, or calling other methods associated with the add and remove methods (such as addAll).

Example of addAll:

/**
 * @author wangmengjun
 *
 */
public class ArrayExample {
 
  public static void main(String[] args) {
 
    /**使用变长参数*/
    List<String> array1 = Arrays.asList("Welcome", "to", "Java", "world");
    array1.addAll(Arrays.asList("AAA", "BBB"));
  }
 
}
Copy after login

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)
Copy after login

Example of

set:

/**
 * @author wangmengjun
 *
 */
public class ArrayExample {
 
  public static void main(String[] args) {
 
    /**使用变长参数*/
    List<String> array1 = Arrays.asList("Welcome", "to", "Java", "world");
    System.out.println(array1);
     
    //将Java替换成hello
    array1.set(2, "hello");
    System.out.println(array1);
  }
 
}
Copy after login

It is precisely because the internal class ArrayList of Arrays overrides the set method that the above program can run normally and will no longer throw UnsupportedOperationException.

The results are as follows:

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

Usage scenarios

Judging from the above examples and 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 length of the generated List is fixed; modification operations can be performed (for example, modifying an element at a certain position); operations that affect the length (such as add, remove, etc.) cannot be performed. An UnsupportedOperationException will be thrown.

Arrays.asList is more suitable for scenarios where you already have array data or some elements and need to quickly build a List, which is only used for reading operations without adding or deleting operations.

If you want to quickly obtain a list that can be added, deleted, modified, and checked based on known array data, a relatively simple method is as follows:

Reuse the java.util.ArrayList wrapper layer.

/**
 * @author wangmengjun
 *
 */
public class ArrayExample {
 
  public static void main(String[] args) {
 
    /**使用变长参数*/
    List<String> array1 = new ArrayList<>(Arrays.asList("Welcome", "to", "Java", "world"));
    System.out.println(array1);
 
    array1.add("Cool~~~");
    System.out.println(array1);
 
  }
 
}
Copy after login

The results are as follows:

[Welcome, to, Java, world]
[Welcome, to, Java, world, Cool ~~~]

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more java source code analysis and detailed explanation of the Arrays.asList method, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

See all articles