当前位置:网站首页>Be careful, these hidden "bugs" of "array" to "collection"“

Be careful, these hidden "bugs" of "array" to "collection"“

2022-06-11 01:38:00 Haoshuo programming

"Array.asList"

First, let's popularize science to unfamiliar brothers :

Array.asList() Method to convert an array to a collection

For friends who often do data processing

It should be no stranger

But then again

This method has several hidden " pit "

There may be a fraternity attack

Let's find out next

It's said that sharing with likes is better

A pit : Cannot directly convert arrays of basic data types

Wrong cases :

// Define basic data types int An array of class 
int[] arr = {1, 2, 3};
// Use Array.asList() Method to a collection 
List list = Arrays.asList(arr);
// Output the converted set information 
log.info("list:{} size:{}", list, list.size());

Expected output :

list:[1, 2, 3] size:3

Console actual output :

list:[[[email protected]] size:1

Obviously hidden ” pit “ There is ,

An array with three elements has only one element left after conversion, and there is a problem with the data type .

Cause analysis :

although int Can be boxed into packing class integer, but int The array cannot be boxed into integer Array .

Pit removal scheme :

1、Java8 The above provides Arrays.stream Method cast

int[] arr1 = {1, 2, 3};
List list1 = Arrays.stream(arr1).boxed().collect(Collectors.toList());
log.info("list:{} size:{}", list1, list1.size());

2、 Direct use of packaging integer Define an array

Integer[] arr2 = {1, 2, 3};
List list2 = Arrays.asList(arr2);
log.info("list:{} size:{}", list2, list2.size());

Modified console output :

list:[1, 2, 3] size:3

We got the results we expected , The first pit, we Successful pit removal La !

Brother, don't be stingy with your praise ! It's the power I continue to output , Let's continue to get out of the pit :

Pit two : The converted collection cannot add or delete elements

Wrong cases :

// This time we use the reference class String Array 
String[] arr = {"1", "2", "3"};
List list = new ArrayList(Arrays.asList(arr));
try {
// Try to convert to list Additional elements 
list.add("5");
} catch (Exception ex) {
ex.printStackTrace();
}
// After the transformation , Modify the value of the original array 
arr[1] = "4";
// Output the original array 、 The converted set 
log.info("arr:{} list:{}", Arrays.toString(arr), list);

Expected output :

arr:[1, 4, 3] list:[1, 2, 3, 5]

Console actual output :

// First of all list Exception to append element 
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at org.geekbang.time.commonmistakes.collection.aslist.AsListApplication.wrong2(AsListApplication.java:41)
at org.geekbang.time.commonmistakes.collection.aslist.AsListApplication.main(AsListApplication.java:15)
// Element output 
arr:[1, 4, 3] list:[1, 4, 3]

According to the console output ,

We're not just going to list Failed to append element ,

Our changes to the elements in the original array also affect the collection list,

This is the third pit :

Pit three : Changes to the original array will affect the data after conversion List

Cause analysis :

Actually Arrays.asList Method List It's not what we expect java.util.ArrayList, It is Arrays Of Inner class ArrayList.

The difference between the two is ,ArrayList The inner class inherits from AbstractList class , and There is no overriding parent add Method , So the above exception occurs .

The third pit is because ArrayList Directly using the original array , So it will have the effect of sharing arrays with each other .

If we pass Arrays.asList To obtain the List Leave it to other methods , It's easy because you share arrays , Modify each other to produce implicit “bug”.

It's hard to find a reason for this problem , Be very careful .

Pit removal scheme :

The method is not difficult to guess ,

We just need to use a real java.util.ArrayList To store the converted list that will do

String[] arr = {"1", "2", "3"};
// use java.util.ArrayList Receive the converted list
List list = new ArrayList(Arrays.asList(arr));
arr[1] = "4";
try {
list.add("5");
} catch (Exception ex) {
ex.printStackTrace();
}
log.info("arr:{} list:{}", Arrays.toString(arr), list);

Modified console output :

arr:[1, 4, 3] list:[1, 2, 3, 5]

The output meets our expectations .

We new Of ArrayList You can do add operation 、 It is separated from the previous array .

This is a good solution to the problem !

 look out !" Array " turn " aggregate " These hidden "bug"

Today we discussed Array.asList() The three pitfalls of the method

If you feel useful, remember Like sharing Oh

The official account of the same name Haoshuo programming   | Programming information , e-book , The installation package is packed and taken away

I also went to prepare some paper and kept it until I cried !

 

原网站

版权声明
本文为[Haoshuo programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020624519292.html

随机推荐