Write articles carefully and share with your heart.

Personal website: Yasinshaw.com

Public number: XY’s technical circle

I ran into a problem with the arrays.aslist method the other day:

Remove (ArrayList, ArrayList); remove (ArrayList, ArrayList, ArrayList);

After a closer look at the source code, it turns out that the ArrayList is not an ArrayList from the java.util package we normally use, but a private inner class from the Arrays class. This inner class inherits AbstractList, but does not override methods like remove or add. So its length is immutable, which is exactly what the Arrays class is designed for.

The reason we use arrays.aslist () is to get a List with as little code as possible. This is a common requirement when writing unit tests.

After Java 9, you can use list.of () instead of arrays.aslist (). But inside it is also an immutable List returned:

But it’s important to note that there are some small differences. For example, the List returned by arrays.aslist () is set, but the list.of () is not.

What if you want to use this brevity, but you want to be able to add or remove elements later? You can write your own method like this:

Of course, there are open source libraries to help us do this! Google Guava provides a Lists class with some newArrayList methods:

The Google Guava library provides a number of useful utility classes to try out.

More articles, welcome to pay attention to the public number: XY’s technical circle