当前位置:网站首页>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
边栏推荐
- Ansible practical Series II_ Getting started with Playbook
- Julia 1.6 1.7 common problem solving
- 一键提取pdf中的表格
- Django running error: error loading mysqldb module solution
- Remember a company interview question: merge ordered arrays
- AcWing 1298. Solution to Cao Chong's pig raising problem
- Some notes of MySQL
- Remember the interview algorithm of a company: find the number of times a number appears in an ordered array
- 【博主推荐】C# Winform定时发送邮箱(附源码)
- [recommended by bloggers] asp Net WebService background data API JSON (with source code)
猜你喜欢
QT creator test
Idea import / export settings file
Install mongdb tutorial and redis tutorial under Windows
QT creator create button
Case analysis of data inconsistency caused by Pt OSC table change
PyCharm中无法调用numpy,报错ModuleNotFoundError: No module named ‘numpy‘
Leetcode 461 Hamming distance
AcWing 1298. Solution to Cao Chong's pig raising problem
[free setup] asp Net online course selection system design and Implementation (source code +lunwen)
【博主推荐】SSM框架的后台管理系统(附源码)
随机推荐
PyCharm中无法调用numpy,报错ModuleNotFoundError: No module named ‘numpy‘
Ansible实战系列一 _ 入门
QT creator uses Valgrind code analysis tool
How to build a new project for keil5mdk (with super detailed drawings)
[recommended by bloggers] C # generate a good-looking QR code (with source code)
Leetcode 461 Hamming distance
Pytorch基础
QT creator shape
AcWing 1298. Solution to Cao Chong's pig raising problem
SSM integrated notes easy to understand version
[ahoi2009]chess Chinese chess - combination number optimization shape pressure DP
[recommended by bloggers] asp Net WebService background data API JSON (with source code)
Introduction to the easy copy module
Image recognition - pyteseract TesseractNotFoundError: tesseract is not installed or it‘s not in your path
Heating data in data lake?
Idea import / export settings file
[free setup] asp Net online course selection system design and Implementation (source code +lunwen)
图像识别问题 — pytesseract.TesseractNotFoundError: tesseract is not installed or it‘s not in your path
Swagger, Yapi interface management service_ SE
Django running error: error loading mysqldb module solution