String中==和equal()的区别
来源:互联网 发布:学生基本信息表sql 编辑:程序博客网 时间:2024/05/18 03:32
.equal()判断的是两个字符串字面值是否相等
下面是JDK源码String类中的equals()方法.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
我们可以看到,equals()方法首先通过this指针来判断两个对象是否相等,如果相等返回true,不相等的话则检查传入的参数是否是一个String实例,如果是的话得到参数的长度并且与要比较的String对象长度做比较如果不相等则返回字符串不相等,如果相等则分别得到两个字符串内的字符组,循环对两个字符串组一一进行比较,如果全相等的话则返回两个字符串相等,否则返回两个字符串不相等。
不同对象总是产生不同的散列值,即便是他们是相等的值也可以。
下面是一些测试==方法的类别:
/ These two have the same value
new String("test").equals("test") // --> true
// ... but they are not the same object
new String("test") == "test" // --> false
// ... neither are these
new String("test") == new String("test") // --> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" // --> true
// concatenation of string literals happens at compile time,
// also resulting in the same object
"test" == "te" + "st" // --> true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) // --> false
// interned strings can also be recalled by calling .intern()
"test" == "!test".substring(1).intern() // --> true
我们都应该知道==相对于equal方法来说更轻量级,在你能保证两个string值指向同一个对象时你就可以使用==方法并且它能带给你性能上的提升。当然,这种提升也是很少的。
equal()方法的使用
某些情况下我们要覆写equal()的方法,我们也一定要覆写.tohashcode()方法,不然可能带来意想不到的的结果
- String中==和equal()的区别
- String比较中==和equal()的区别
- String中"=="和equal()的区别
- java String字符串中 ==和equal区别
- String 类的equal 和 == 的区别?
- android String equal 和 ==的区别
- java 中String equal 和==的区别,以及StringBuffer
- Java中“==”和equal()的区别
- java中“==”和“equal()”的区别
- String 中== 、equal和null
- Java String 中equal 和==
- = 和 equal 的区别
- java中equal()与==的区别(顺便谈谈String,stringBuffer,StringBuilder)
- java中“==”和equal()的区别以及equal()的重载
- java中equal 和 ==的区别
- Java中equal和"=="的区别
- java中equal()方法和==的区别
- Java中equal和"=="的区别
- object 知识总结(案例学习)
- 我的思维导图
- poj2421
- Mysql中特殊字符的使用注意事项
- 开启笔记本win7的虚拟热点笔记本变成wifi教程
- String中==和equal()的区别
- HDU 4165Pills
- Servlet分析(3) servletRequest与 servletResponse
- 我写过的软件之LoaderHst-TestView
- 读写Excel文件最好还是用Office VBA之类的,C++读写原来这么不容易
- Pat(Advanced Level)Practice--1035(Password)
- 计算机考研
- com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax;
- 机房收费系统-状态图与活动图