Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the pits of Arrays.asList that are easy to use in Java?

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what are the pits in the Arrays.asList that are easy to use in Java". In the daily operation, I believe that many people have doubts about the pits in the Arrays.asList that are easy to use in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "which pits are good for Arrays.asList in Java". Next, please follow the editor to study!

Easy to use asList

In the process of developing or writing test cases, Arrays.asList () is often used to quickly and easily convert an array into a List. For example:

List list = Arrays.asList ("Book", "Pen", "Desk", "Cup")

When we refer to Arrays.asList () statically:

Import static java.util.Arrays.asList

You can write directly like this:

List list = asList ("Book", "Pen", "Desk", "Cup"); hidden pit base types cannot be generalized

Execute the following test case:

@ Testpublic void size () {int [] nums = {1,2,3,4,5,6}; List list = asList (nums); assertEquals (nums.length, list.size ());}

The result is failed:

Java.lang.AssertionError: Expected: 6Actual: 1

Why is it that there is only one element when it is converted to List in an array of six elements?

The source code doesn't lie, so let's look at the code:

Public static List asList (T... A) {return new ArrayList (a);}

Through the source code, we can know that the input parameter of the asList () method is generic, and it is impossible to generalize the basic type of int, so the function treats the whole array as a whole (the array is a reference type and can be generalized). The final result is List, not List.

If we need List, we can deal with it in two ways:

@ Testpublic void listForInt () {/ / method 1: initialize the array to Integer, automatically boxing Integer [] nums = {1, 2, 3, 4, 5, 6}; List list = asList (nums); assertEquals (nums.length, list.size ()); / / method 2: without passing in the whole, automatically boxing list = asList (1, 2, 3, 4, 5, 6); assertEquals (6, list.size ());}

The result returned by the above two methods is List.

Cannot be modified

Happily transformed into List, is ready to do a big fight, to carry out the routine operation of List, but found that the operation can not:

@ Testpublic void listAdd () {List list = asList ("Book", "Pen", "Desk", "Cup"); list.add ("Box"); assertEquals (5, list.size ());}

The error report is as follows:

Java.lang.UnsupportedOperationException at java.util.AbstractList.add (AbstractList.java:148) at java.util.AbstractList.add (AbstractList.java:108) at com.larry.basic.AsListTest.listAdd (AsListTest.java:42)

Having to look at the source code again, we can see that although the result returned by the asList () method is ArrayList, it is different from our usual ArrayList:

The most commonly used one is java.util.ArrayList, and the bottom layer is the List of variable array. Java.util.Arrays.ArrayList is a static inner class of Arrays, and the underlying is the List of the array of final. They are not of the same class.

Java.util.Arrays.ArrayList does not override methods such as add/remove/clear, so the method of the parent class AbstractList is called, and the method of the parent class is as follows:

Public boolean add (E e) {add (size (), e); return true;} public void add (int index, E element) {throw new UnsupportedOperationException ();} public E remove (int index) {throw new UnsupportedOperationException ();}

So, these methods are actually uncallable and throw an exception UnsupportedOperationException.

Modify the side effects of the operation set

But is the result of asList () really immutable? Not really. Although Arrays.ArrayList does not override the add/remove/clear method, it overrides the set () method:

@ Overridepublic E set (int index, E element) {E oldValue = a [index]; a [index] = element; return oldValue;}

We can replace the elements in it. It is easy to understand that the underlying final array is immutable in size, but the elements of the array are variable. Because of this feature, the following problems may arise:

@ Testpublic void listSet () {String [] arr = {"Book", "Pen", "Desk", "Cup"}; List list = asList (arr); list.set (0, "New Book"); assertEquals ("New Book", list.get (0)); assertEquals ("Book", arr [0]);}

The last sentence of the code reported an error, and when the first element of the List was changed, the first element of the array was also changed because they all pointed to the same array address. If you don't pay attention, you will produce different results than you expect.

If you want to create a new List, you can use the following methods:

List list = new ArrayList (asList (arr))

Because new ArrayList () will copy a new array with the method Arrays.copyOf ().

At this point, the study of "what are the pits of Arrays.asList that are easy to use in Java" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report