" String ".equals("String")==true
解决方案 »
- java新手求问刚做了一个小项目,下面是我的java连接sql2000的代码,请问现在要连接mysql代码应该如何改动
- 关于同步代码块,请教各位
- 该怎么入门JAVA的圣经
- java票据打印得问题
- 请教一个关于jtree鼠标右键的问题
- 为什么是这个结果 ,怪事。感谢。
- 关于java学习心得!
- 请教高手,请问在java中调用ocx或者com组件,如何收到它们的事件以及传出参数?
- 请问各位大虾!后缀名为jar的文件怎样把它发布到java的平台中,使用呀!!我用的是j2eeSDK
- tomcat4中如何配置mail
- 请大家帮忙,作个简单的东东
- 请问:现在java客户端一般采用哪几种技术以及它们的优劣?发言者均给分!
The instance of "String ".trim() != the instance of "String".
而且你也说了,trim()在return的时候可能是返回了一个新的String ,那么这个新的"String"(即去掉头尾的空白)和右边的“String”应该都是指向pool里的那个啊。我们都知道String s1="2222";
String s2="2222";
s1==s2 true
Method equals() is different.
it's the same as ==,if it isn't overriden by the object class.
many classes override the method equals().In this case this mehtod will check that content of the object is the same or not,not address.
String s1="1111";
String s2="2222";
s1==s2 true;
吧那么" String ".trim()这个语句是返回一个新的String对象,值为"String".我认为这里没有用new关键字,所以还是指向pool中的那个"String"那么这么理解的话" String ".trim()=="String"应该是true啊
It is just like "new String("String");". So it is not in the pool at all!However, your question is super good!
以下是我的测试:
1、
String s1=new String(" String ");
System.out.println((s1==" String "));
返回true
2、
String s1=new String(" String ");
System.out.println((s1==" String "));
返回false结论:
" String ".trim()虽然返回的是一个新的String对象"String",但它相当于是new String("String")和上面的2是一样的。若new String(" String ") 还是和==" String "指向同一个地址的话,那就没办法实现在程序中有两个一样的字串但属于不同的地址的String对象了。
1、
String s1=" String ";
System.out.println((s1==" String "));
返回true
"" String ".trim它相当于是new String("String")"
"String".trim()这句话应该是相当于new String("String")了吧
那么再来一遍!再来一个"String".trim(),也相当于又new String("String")了吧
OK,那么这么想的话,因为
new String("String")=new String("String");明显是false吧
那你猜猜"String".trim()=="String".trim()
是true还是false呢?public class SL275
{
public static void main(String[] args)
{
System.out.println("String".trim()=="String".trim());
System.out.println(new String("String")==new String("String"));
}
}我试过了,答案是1.true 2.false,你说怎么解释?
System.out.println((s1.trim()==s1.trim()));你说是什么?
答案是false!
TIJ :
You can see that every String method carefully returns a new String object when it’s necessary to change the contents. Also notice that if the contents don’t need changing the method will just return a reference to the original String. This saves storage and overhead.Java的字符串处理函数有如把 字符串当不可变变量传入函数(类似C++中的const )
对字符常数(immutable)和new String()得到的处理方式是不一样的,
//直接对字符常数的操作都得到同一个对象,所以("String".trim()=="String".trim());因为:
String s2=" String ";
System.out.println(s2.trim()==" String ".trim());
得到的是false!哈哈我知道问题在哪了:
System.out.println(" String ".trim()==" String ".trim() );
得到的是false!If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.当没有空格时 trim()是不会返回一个新的对象的!!!