本帖最后由 陈帅雷 于 2011-12-23 12:18 编辑
JAVA 中的 "==" 和 "equals" ,"InstanceOf"
"==" 和 "equals" 是在java引用变量比较中用来比较两个引用变量是否都指向同一个对象的.但是如果用"equals" 做比较时, 如果引用变量的的引用类型和变量值如果都相同的话,那结果为真.
InstanceOf 用来判断一个引用类型所引用的对象是否为一个类的实例变量.
Object中的equals方法准则:
当参数obj引用的对象与当前类的对象为同一个对象时,就放回true,否则为false.
public boolean equals(Object obj){
if(this==obj){
return true;
}else{
return false;
}
}
举例:
package p;
public class Eq {
public static void main(String[] args){
//Eq eq = new Eq();
String name = new String("Tom");
if(name == "Tom"){
System.out.println("Hello,Tom");
}else{
System.out.println("Sorry,I don't know you");
}
if(name.equals("Tom")){
System.out.println("Hello,Tom");
}else{
System.out.println("Sorry,I don't know you");
}
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean(true);
if(b1 == b2){
if(b1.equals(b2)){
System.out.println("a");
}else{
System.out.println("b");
}
}else{
if(b1.equals(b2)){
System.out.println("c");
}else{
System.out.println("d");
}
}
//结果为 c
Boolean b3 = new Boolean(true);
Object obj = (Object)b3;
if(b3 == obj){
if(b3.equals(obj)){
System.out.println("aa");
}else{
System.out.println("bb");
}
}else{
if(b3.equals(obj)){
System.out.println("cc");
}else{
System.out.println("dd");
}
}
//结果为 aa
String a = "hello";
String b = new String(a);
char[] c ={'h','e','l','l','o'};
System.out.println(a=="hello");
System.out.println(a==b);
System.out.println(a.equals(b));
System.out.println(a.equals(c));
}
}
例子2: (InstanceOf)
package p;
public class Animal extends Creature{
String name = "abc";
public Animal(){}
public Animal(String name){
this.name = name;
}
public boolean equals(Object obj){
if(this == obj){
return true;
}
if(!(obj instanceof Animal)){
return false;
}
final Animal ani = (Animal)obj;
if(this.name.equals(ani.name)){
return true;
}else{
return false;
}
}
public static void main(String[] args){
Dog dog = new Dog();
Cat cat = new Cat();
Creature creature = dog;
Animal animal = new Cat();
Animal animal1 = new Animal("abc");
Animal animal2 = new Animal("abc");
System.out.println(dog == creature);
System.out.println(dog == animal);
System.out.println(animal1.equals(animal2));
//如果不覆盖 equals 方法 ,则 animal1.equals(animal2) 结果为false
}
}
|