1.我查了JDK文档,说Object.equals()是两个非空引用的比较,我理解的是比较两个引用是否指向同一个对象,即这两个引用所保存的内容(对象地址)是否相同。不知道我的理解对不对?还有,如果是一个引用和一个对象比较,内部是如何处理的?如:String s="hello"; s.equals("hello");
2.String s1="hello";
String s2="hello";
System.out.println(s1.equals(s2);); //true
我感觉s1和s2是指向不同对象的不同引用,为什么为true?
3.Object.equals()和"=="有什么区别?
请各位不吝赐教!!!!十分感谢!!~~
2.String s1="hello";
String s2="hello";
System.out.println(s1.equals(s2);); //true
我感觉s1和s2是指向不同对象的不同引用,为什么为true?
3.Object.equals()和"=="有什么区别?
请各位不吝赐教!!!!十分感谢!!~~
当时我也是糊涂了很长时间的。
还有不明白的地方:
1.,"==则是你理解的那样,必须是同一个对象,指向同一个地址。"
String s1="hello";
String s2="hello";
System.out.println(s1==s2); 这个同样是true
2."equals是对值进行比较"
对对象而言,“值”是个什么概念?不能理解,我感觉对字符串对象还有基本类型的包装类而言有值,对一般的对象而言值指的是什么?
谢谢您的留言。我查了JDK文档:
“equals:
public boolean equals(Object anObject)
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.
Overrides:
equals in class Object”
文档上说的是“override”而不是重载,我感觉也是。但如果是"override"的话,String调用equal()时是调用自己的equal(),文档上说String的equal()是必须和一个特定对象比较(“Compares this string to the specified object”),那为什么两个引用的比较也是可行的??
String s1="hello";
String s2="hello";
System.out.println(s1.equals(s2);); //true如果是重载的话是可以的,但java的做法是override,不知道是我理解错了,还是有其他原因???
请您指教!!!!
String s1="hello";
String s2="hello";
这里比较会发现 s1 == s2 是因为编译器会在编译的时候发现两者相同,所以指向同一个对象以节省内存。如果s2是动态生成的(写成 String s2 = "h" + "ello"是会被编译器优化的成"hello"的)
就不会==
2.
我是用词有点问题,我意思就是String覆盖Object的equals方法,所以s1.equals(s2)自然就调用了String的方法
public static void main(String[] args)throws IOException{
System.out.println("please key the 'y'!");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String s=in.readLine();
if(s.equals("y")||s.equals("Y"))//这里用“==”就不行了
System.out.println("I may do something.");
}
new String("test1").equals(null) = true;其实最后比较的准则是先矫正内容,在按字节玛核对字符串
这个不对,equals是用来比较对象的值的。equals再java中用来比较String,stringbuffer
==比较其他的
所有类型的祖先类Object中有一个equals方法,它的本意是比较两个对象的引用是不是一样。
我们创建的类中也有这个方法,如果你不改变它,它默认的行为就是比较两个对象的引用是不是一样。这时equals就等同==的效果。
而String类把equals方法改变了,让他去比较两个对象的引用的内容是不是一样。
我感觉如果是字符串对象或是基本类型的包装对象的值我可以理解,对于一般对象而言,它的值是指什么???
基于j2ee平台的大型电子商务网站源代码下载 :本源代码可以帮助大家了解大型物品买卖和交换网站如淘宝,易宝乐等网站的开发和创建。
下载地址: http://www.ebaole.com/sourcedown.html
并且开辟了一个社区专门为大家提供源代码的交流和讨论!