当前位置:网站首页>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
边栏推荐
- Database advanced learning notes -- SQL statement
- [download app for free]ineukernel OCR image data recognition and acquisition principle and product application
- Learn winpwn (2) -- GS protection from scratch
- Redis的基础使用
- In the era of DFI dividends, can TGP become a new benchmark for future DFI?
- 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
- [蓝桥杯2021初赛] 砝码称重
- [蓝桥杯2017初赛]包子凑数
- 01项目需求分析 (点餐系统)
- Picture coloring project - deoldify
猜你喜欢
[number theory] divisor
[recommended by bloggers] asp Net WebService background data API JSON (with source code)
Introduction and use of automatic machine learning framework (flaml, H2O)
Did you forget to register or load this tag 报错解决方法
机器学习--人口普查数据分析
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
Django running error: error loading mysqldb module solution
UDS learning notes on fault codes (0x19 and 0x14 services)
PyCharm中无法调用numpy,报错ModuleNotFoundError: No module named ‘numpy‘
Learn winpwn (2) -- GS protection from scratch
随机推荐
What does usart1 mean
JDBC principle
项目实战-后台员工信息管理(增删改查登录与退出)
Django running error: error loading mysqldb module solution
基于apache-jena的知识问答
AcWing 1294.樱花 题解
Request object and response object analysis
There are three iPhone se 2022 models in the Eurasian Economic Commission database
Solve the problem of installing failed building wheel for pilot
【博主推荐】asp.net WebService 后台数据API JSON(附源码)
[蓝桥杯2020初赛] 平面切分
天梯赛练习集题解LV1(all)
报错解决 —— io.UnsupportedOperation: can‘t do nonzero end-relative seeks
QT creator custom build process
Database advanced learning notes -- SQL statement
Detailed reading of stereo r-cnn paper -- Experiment: detailed explanation and result analysis
连接MySQL数据库出现错误:2059 - authentication plugin ‘caching_sha2_password‘的解决方法
Ansible实战系列一 _ 入门
Julia 1.6 1.7 common problem solving
解决安装Failed building wheel for pillow