String三个注意事项
来源:互联网 发布:投资项目经济评价软件 编辑:程序博客网 时间:2024/06/07 10:23
1、检查String是否相等
如上文提到的,检查String是否相等最好要使用equals方法,尽量少使用==操作符。
String cmower ="cmower";System.out.println("cmower" == cmower);//trueSystem.out.println("cmower".equals(cmower));//trueSystem.out.println("cmower".substring(0, 3) == "cmo");//falseSystem.out.println("cmower".substring(0, 3).equals("cmo"));//true
1- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
- ==操作符确定的是两个String是否放在同一个位置上。
- “cmower”字符串和cmower变量指向的引用就是在同一个位置上,所以==比较结果为true。
- 在Java虚拟机上,只有字符串常量是共享的(”cmower”字符串和cmower变量共享了同一个地址)。但是对于substring产生的结果就不共享了。
- 对于equals,比较的则是两个对象是否具有相同的字符集。
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
2、String不可变
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
“s”是一个字符串对象,你怎么也不能把这个对象变成“S”。也就是说小s和大S尽管是双胞胎,但她们俩注定都不能成为对方。
3、+与StringBuilder
首先,我们先来看对于+操作符,在Java虚拟机下是如何工作的。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
对于add1和add2方法,你认为Java虚拟机的工作方式一样吗?
闭上眼睛10秒钟,先想一会。
我们来揭晓答案:
差别是不是很大?
这说明,+操作符在拼接String时,会根据情况做一定的选择。比如add1方法,Java会new 一个StringBuilder对象,来对abcd100进行append操作,之后再toString出来。
那么也就说,Java会自动会为我们优化代码,以后我们尽管使用+操作符就行了。但事实并非如此,再来看一串代码。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
这个时候,你选择用sb方法还是plus方法?
再闭上眼睛10秒钟,想一下你的答案。
javap执行结果如下:
看得出plus方法的8-34行是一个循环,11行时创建了StringBuilder对象,也就是在循环内。这个方法执行了10次,那么也就创建了10个StringBuilder对象。
再来看sb方法的结果:
显而易见,StringBuilder对象只有一个。在使用StringBuilder时,尽量少“在append方法的参数中使用+操作符”:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
这样做糟糕至极:
“a” + b时又重新创建了StringBuilder对象。
总结如下,
1. 在进行循环多次拼接String时,用StringBuilder而不用+操作符!
2. +操作符只用于少量字符串变量拼接,在内存中操作,性能更高!
3. append方法的参数少用+操作符! - String三个注意事项
- Block 三个注意事项
- PLC编程时三个注意事项
- String,String[],string三个用法和意思
- String 使用注意事项
- java String注意事项
- 使用string 的注意事项
- String的注意事项
- String三个空的区别
- 三个double TO string对比
- ViewPager的三个注意事项(bug)
- ansi string TO PWideChar注意事项
- string 的erase方法注意事项
- Lua的string.format 注意事项
- String.split()函数使用注意事项
- List转String时注意事项
- map、string使用的注意事项
- Java String.split()方法注意事项
- React Native之DrawerLayoutAndroid仿网易云音乐滑动菜单
- 用SHELL脚本自动化安装Nagios服务器端和客户端的
- 插入排序
- DelphiXE Ansi字符串UTF-8编码判断
- PAGE_ALIGN 详解 纯属原创 转载注明出处
- String三个注意事项
- 安卓解压zip文件,解压后多级目录显示
- Commit message 和 Change log 编写指南
- Android Dalvik虚拟机内存分配问题
- 支持向量机通俗导论(理解SVM的三层境界)
- 【上机笔试之三】快速排序
- 摘要(Hash)算法总结
- Maven安装配置Repository及关联Eclipse
- android问题之--VT-x is disable in bios