" String ".equals("String")==true
解决方案 »
- JSP乱码
- 咨询一问题:多线程,如果彻底终止线程呢?
- Map<String,List<Map<String,String>>>
- 求给此计算其增加两项功能(此计算器目前正确的) 谢谢大人喽
- 一个castor转换难题啊。有人帮我一下吗?
- 编译声称的class文件或者是jar文件是否可以与其他语言交互的?
- 如何访问内部类?
- 关于Lomboz的一个问题,请大家帮忙看看
- java怎么获取面板里子面板里标签的文本?
- 我想在任何地方使用package aaa;都能使aaa目录生成在同一个地方,而不是当前目录?
- 请大家帮忙,作个简单的东东
- 请问:现在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()是不会返回一个新的对象的!!!