当前位置:网站首页>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
边栏推荐
- [recommended by bloggers] asp Net WebService background data API JSON (with source code)
- 打开浏览器的同时会在主页外同时打开芒果TV,抖音等网站
- Learning question 1:127.0.0.1 refused our visit
- [ahoi2009]chess Chinese chess - combination number optimization shape pressure DP
- [蓝桥杯2017初赛]包子凑数
- QT creator specify editor settings
- QT creator shape
- 【博主推荐】C#MVC列表实现增删改查导入导出曲线功能(附源码)
- error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_s instead
- [蓝桥杯2020初赛] 平面切分
猜你喜欢
Copie maître - esclave MySQL, séparation lecture - écriture
double转int精度丢失问题
Solution: log4j:warn please initialize the log4j system properly
CSDN markdown editor
[recommended by bloggers] C MVC list realizes the function of adding, deleting, modifying, checking, importing and exporting curves (with source code)
UDS learning notes on fault codes (0x19 and 0x14 services)
How to build a new project for keil5mdk (with super detailed drawings)
AcWing 242. A simple integer problem (tree array + difference)
Asp access Shaoxing tourism graduation design website
MySQL与c语言连接(vs2019版)
随机推荐
Learn winpwn (3) -- sEH from scratch
[recommended by bloggers] C WinForm regularly sends email (with source code)
[free setup] asp Net online course selection system design and Implementation (source code +lunwen)
一键提取pdf中的表格
Neo4j installation tutorial
Ansible实战系列三 _ task常用命令
[recommended by bloggers] C # generate a good-looking QR code (with source code)
[download app for free]ineukernel OCR image data recognition and acquisition principle and product application
Request object and response object analysis
Ansible practical Series II_ Getting started with Playbook
Some notes of MySQL
QT creator test
虚拟机Ping通主机,主机Ping不通虚拟机
L2-006 树的遍历 (25 分)
Software testing and quality learning notes 3 -- white box testing
[recommended by bloggers] background management system of SSM framework (with source code)
[recommended by bloggers] asp Net WebService background data API JSON (with source code)
Cookie setting three-day secret free login (run tutorial)
Solution: log4j:warn please initialize the log4j system properly
报错解决 —— io.UnsupportedOperation: can‘t do nonzero end-relative seeks