当前位置:网站首页>About string immutability
About string immutability
2022-07-06 11:23:00 【ysds20211402】
from : Micro reading https://www.weidianyuedu.com/content/2217491421632.html
One 、 Explain the background
I have a system here , Provide a RPC Interface to send SMS . To call my interface externally, you need to pass in the phone number and other parameters , I'm in charge of parsing these parameters 、 Do some business processing , Then call the SMS channel to send SMS .
When the interface of SMS channel provider is called , I will store the records sent this time ( Deposit in MySQL in ), In the same way, SMS channel will return the receipt sent or failed to me , I'll also put it in storage ( Deposit in MySQL in ).
On that day , Someone came to me , Say a cell phone number can't receive a message , Users don't block SMS ( In arrears 、 To turn it off ) Wait a minute , I just can't get messages .
So I went to check , First of all, I'll go first DB Look inside for the corresponding sending record , Find out that this record exists , And in DB I can't see anything unusual .
therefore , This precludes the operation being intercepted in the middle of the way ( Because it's in storage , Must have called the SMS operator's interface )
Later, I went to the journal , Take a look at the call SMS operator's return Result What is the object's information , Then I asked the SMS operators why they might have this problem . The reply over there is :“ If it's part of the mobile phone number that has this situation , Is your cell phone number not trim ah ?”
therefore , I went to the journal again , I found that there was a space behind the cell phone number ( heartache , I couldn't see ). It's very easy to deal with this problem , All I have to do is to check my cell phone number in the entrance trim Just fine .
Two 、 Write code
My side is for Send the same message to multiple cell phone numbers , So my cell phone number is HashSet To receive . Carry out... On the mobile phone number trim I wrote the following code :
// explain :Task object There is one key attribute , This key The type of property is HashSetif (task.getKey() != null && task.getKey().size() > 0) { for (String s : task.getKey()) { s.trim(); }}
The code is simple , I just do two steps :
Judge whether it is null, Not for null Value to traverse the phone number set
For each cell phone number trim
Is there something wrong with the code above ? There must be a problem , No problem. What else do I write .
Write a little Demo, We will find that : In the code of 11 Call on line trim()
After the method , stay 12 Line re output , There will still be spaces .
Code example
2.1 Why is there such an illusion ?
Actually , We are at the beginning of learning Java When , I'm sure to learn String class . It is also clear when studying String yes immutable Of , But there's always a feeling that we put String The object has been changed , Why? ?
Immutable String
I think the first point is : We operate on mutable objects , Some properties of the object have been changed , We think it has been changed . Consider the following code :
HashSet<Student> students = getStudent();for (Student s1 : students) { s1.setName("Java3y");}
After execution , We think it's in HashSet Inside Student All the names of are changed to Java3y 了 , And it's actually the same .
I think the second point is : We usually operate String object , It's all about passing the results of the operation directly to , It looks like the original object has been modified . For example, the following similar code :
// duplicate removal String phone = " 137888888888 ";sendPhone(phone.trim());// Convert to uppercase and output System.out.println(phone.toUpperCase());// ... wait
Back to a new String object
2.2 How to change
Now the problem is known ,String Object is immutable , Yes String Object to operate on ,“ It looks like ” Original String The object has changed , In fact, a new String object .
Back to my question , It's also very easy to solve , hold trim
A good phone number is set to HashSet That's it
边栏推荐
- 一键提取pdf中的表格
- Solution: log4j:warn please initialize the log4j system properly
- Why can't STM32 download the program
- 误删Path变量解决
- AI benchmark V5 ranking
- Install mysql5.5 and mysql8.0 under windows at the same time
- Machine learning -- census data analysis
- 项目实战-后台员工信息管理(增删改查登录与退出)
- Use dapr to shorten software development cycle and improve production efficiency
- [蓝桥杯2021初赛] 砝码称重
猜你喜欢
学习问题1:127.0.0.1拒绝了我们的访问
Machine learning notes week02 convolutional neural network
QT creator runs the Valgrind tool on external applications
QT creator create button
Kept VRRP script, preemptive delay, VIP unicast details
图片上色项目 —— Deoldify
图像识别问题 — pytesseract.TesseractNotFoundError: tesseract is not installed or it‘s not in your path
Learn winpwn (3) -- sEH from scratch
引入了junit为什么还是用不了@Test注解
Neo4j installation tutorial
随机推荐
02 staff information management after the actual project
Record a problem of raspberry pie DNS resolution failure
数据库高级学习笔记--SQL语句
neo4j安装教程
Copie maître - esclave MySQL, séparation lecture - écriture
CSDN markdown editor
error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_s instead
机器学习--人口普查数据分析
[recommended by bloggers] C MVC list realizes the function of adding, deleting, modifying, checking, importing and exporting curves (with source code)
csdn-Markdown编辑器
Ansible实战系列二 _ Playbook入门
Install MySQL for Ubuntu 20.04
AcWing 1298. Solution to Cao Chong's pig raising problem
[AGC009D]Uninity
[Thesis Writing] how to write function description of jsp online examination system
SSM integrated notes easy to understand version
[download app for free]ineukernel OCR image data recognition and acquisition principle and product application
01项目需求分析 (点餐系统)
AcWing 179.阶乘分解 题解
Are you monitored by the company for sending resumes and logging in to job search websites? Deeply convinced that the product of "behavior awareness system ba" has not been retrieved on the official w