String是我们在JAVA中常用的类,对于其操作也十分的多,经常,我们会遇到对2个String的比较,我们应该怎么比较呢?
首先我们来看一下3个测试用例:
1.使用==比较,呵呵。
public void test1(){
String a=new String ("hello ");
String b=new String ("hello ");
System.out .println(a==b);
}
result: false
2.使用equals()方法比较。最常用的。
public void test1(){
String a=new String ("hello ");
String b=new String ("hello ");
System.out .println(a.equals(b));
}
result:true
3.还是使用==比较。略有不同
public void test1(){
String a="hello ";
String b="hello ";
System.out .println(a==b);
}
result:true
经过试验,我们看到2,3都是返回true,但是为啥1却是false?
首先,==比较对于String和其他一些非基本数据类来说是比较的地址,而不是比较其所含的值。真正做到值比较的是 equals()方法。一下它的具体实现
通过String里char数组的比较来完成值的比较。
最后为啥实验3会是true呢?为了提高效率,java为String类提供了串池 。 正如大家所看到的样,Test3中就使用了串池 。当你重新声明一个String型变量为 hello 时,将使用串池 里原来的那个 hello ,而不重新分配内存,也就是说,str2与str1将会指向同一块内存 。所以结果为true。 在Test1中使用了普通对象的声明方式,系统将会为a和b各分配一块内存 。所以结果为false。