当前位置:网站首页>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:3Console actual output :
list:[[[email protected]] size:1Obviously 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:3We 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 !

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 !
边栏推荐
- 云呐|PDA无线固定资产盘点管理系统
- [mavros] mavros startup Guide
- Function of barcode fixed assets management system, barcode management of fixed assets
- 数字ic设计自学ing
- ava. Lang.noclassdeffounderror: org/apache/velocity/context/context solution
- 北京門頭溝區高新技術企業培育支持標准,補貼10萬
- Norme de soutien à la culture des entreprises de haute technologie du district de Mentougou à Beijing, subvention de 100 000 RMB
- 北京密云区高新技术企业培育支持标准,补贴10万
- Using MySQL database in nodejs
- threejs:两点坐标绘制贝赛尔曲线遇到的坑
猜你喜欢
![[ROS introduction] cmakelist Txt and packages XML interpretation](/img/26/bae82a457fb83b2214d2f8c20955e2.jpg)
[ROS introduction] cmakelist Txt and packages XML interpretation

2.0、ROS与PX4通信详解

1.4PX4程序下载

IRS应用发布之十六:H5 应用设计指南

Record the packaging of the googlechrome browser plug-in

Simple select sort and heap sort
![[ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design](/img/63/3193186820215b9babc3d00e1ef20b.jpg)
[ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design

QGC ground station tutorial
![[ROS] review of 2021 ROS Summer School](/img/1c/588d29b60071628c7c9fdce17e8b84.jpg)
[ROS] review of 2021 ROS Summer School

Yunna provincial administrative unit fixed assets management system
随机推荐
Norme de soutien à la culture des entreprises de haute technologie du district de Mentougou à Beijing, subvention de 100 000 RMB
Beijing Mentougou District high tech enterprise cultivation support standard, with a subsidy of 100000 yuan
北京門頭溝區高新技術企業培育支持標准,補貼10萬
Beijing Tongzhou District high tech enterprise cultivation support standard, with a subsidy of 100000 yuan
[path planning] week 1: hodgepodge
Beijing Fangshan District high tech enterprise cultivation support standard, with a subsidy of 100000 yuan
Basic introduction of graph and depth first traversal and breadth first traversal
云呐|PDA无线固定资产盘点管理系统
Support standard for cultivation of high-tech enterprises in Changping District, Beijing, with a subsidy of 100000 yuan
北京门头沟区高新技术企业培育支持标准,补贴10万
中国专利奖申报流程介绍,补贴100万
[VBA Script] extract the information and pending status of all annotations in the word document
北京密云区高新技术企业培育支持标准,补贴10万
北京东城区高新技术企业培育支持标准,补贴10万
How to write this with data and proc without SQL
[ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design
SAS factor analysis (proc factor process, factor rotation and regression method for factor score function)
Application of object storage S3 in distributed file system
2022 recognition requirements for new technologies and new products (services) in Huairou District, Beijing
About mobx