1. == 的使用
1.1 可以使用在基本数据类型和引用数据类型变量中
1.2 比较基本数据类型
比较连个变量保存的数据是否相等(不一定类型要相同)
package com. lchh. javase ;
public class TestEquals {
public static void main ( String [ ] args) {
int a = 10 ;
int b = 65 ;
double c = 10.0 ;
System . out. println ( "a==c " + ( a== c) ) ;
char d = 'A' ;
System . out. println ( "b==d " + ( b== d) ) ;
char e = 65 ;
System . out. println ( "d==e " + ( d== e) ) ;
}
1.3 比较引用数据类型
比较的是两个对象的栈地址是否相同,即是比较两个栈的引用是否指向同一个堆中的对象实体
package com. lchh. javase ;
public class TestEquals {
public static void main ( String [ ] args) {
Sheep s01 = new Sheep ( "tom" , 15 ) ;
Sheep s02 = new Sheep ( "tom" , 15 ) ;
System . out. println ( "s01==s02 " + ( s01== s02) ) ;
String str01 = new String ( "abc" ) ;
String str02 = new String ( "abc" ) ;
System . out. println ( "str01==str02 " + ( str01== str02) ) ;
}
}
class Sheep {
String nameString;
int age;
public String getNameString ( ) {
return nameString;
}
public void setNameString ( String nameString) {
this . nameString = nameString;
}
public int getAge ( ) {
return age;
}
public void setAge ( int age) {
this . age = age;
}
public Sheep ( ) {
super ( ) ;
}
public Sheep ( String nameString, int age) {
super ( ) ;
this . nameString = nameString;
this . age = age;
}
}
2. equals()的使用
2.1 equals()是一个方法,只适用于引用类型的数据
2.2 Object类中的equals()方法
Object类中equals()方法和 == 的作用是相同的
public boolean equals ( Object obj) {
return ( this == obj) ;
}
String类中的equals()方法是比较对象中的内容(通常是属性)是否相同(类似的还有Date File 基本类型的包装类)
public boolean equals ( Object anObject) {
if ( this == anObject) {
return true ;
}
if ( anObject instanceof String ) {
String aString = ( String ) anObject;
if ( ! COMPACT_STRINGS || this . coder == aString. coder) {
return StringLatin1 . equals ( value, aString. value) ;
}
}
return false ;
}
2.3 代码示例
package com. lchh. javase ;
public class TestEquals {
public static void main ( String [ ] args) {
Sheep s01 = new Sheep ( "tom" , 15 ) ;
Sheep s02 = new Sheep ( "tom" , 15 ) ;
System . out. println ( "s01.equals(s02) " + ( s01. equals ( s02) ) ) ;
String str01 = new String ( "abc" ) ;
String str02 = new String ( "abc" ) ;
System . out. println ( "str01.equals(str02) " + ( str01. equals ( str02) ) ) ;
}
}
class Sheep {
String nameString;
int age;
public String getNameString ( ) {
return nameString;
}
public void setNameString ( String nameString) {
this . nameString = nameString;
}
public int getAge ( ) {
return age;
}
public void setAge ( int age) {
this . age = age;
}
public Sheep ( ) {
super ( ) ;
}
public Sheep ( String nameString, int age) {
super ( ) ;
this . nameString = nameString;
this . age = age;
}
}
输出结果如下: 实体类继承了object类,用的是Object类中的equals()方法 String类重写了equals()方法,所以比较的是属性值