基本类型:Java语言提供了八种基本类型。六种数字类型(四个整数型,两个浮点型),一种字符类型,还有一种布尔型。
引用类型:在Java中,引用类型的变量非常类似于C/C++的指针。引用类型指向一个对象,指向对象的变量是引用变量。
- 对象、数组、字符串都是引用数据类型。(记住:所有new出来的都是引用数据类型)
- 所有引用类型的默认值都是null。
- 一个引用变量可以用来引用任何与之兼容的类型。
- 例子:Student stu1=new Student; int[] arr = new int[3];
对于“==”,先搞清楚两个比较的区别:基本数据类型比较的是相等性(值是否相等),引用数据类型比较的是同一 性(地址是否相等)。 相等性和同一性:你借用小皮的棒球,用完马上还回去。这是同一性(同一个棒球) 你借用小皮的棒球,不小心丢了,只能再买一个还回去。这是相等性(都是棒球但已经不是原来的那个了)
a.基本数据类型(相等性)使用 :==
这里“==”比较的是相等性
对于基本数据类型在JVM中内部,已经具备这样的指令,所以可以直接用“==”比较值是否相等。
public class Compare {
public static void main(String[] args) {
int a=0;
int b=0;
if(a==b){
System.out.println("true");
}
}
}
-------------------输出true
b.引用数据类型(相等性)使用 : equals()方法
"equals()"可以通过重写来用于对象的比较
如果使用“==”比较引用数据类型,比较的是地址,而无法比较内容。比较的是同一性,不符合我们的需求
public class Compare {
static class Student{
int name;
int stunum; //学号
}
public static void main(String[] args) {
Student stu1=new Student();
Student stu2=new Student();
if(stu1==stu2){
System.out.println("true"); //不执行
}
if(!(stu1==stu2)){
System.out.println("false"); //执行
}
}
}
-------------输出false
这里如果想使用equals()方法比较需要按自己的需求重写该方法,因为我们想比较的是stu1和stu2是不是用一个人,即看学号是不是相等就可以了,我们的需求是看this(引用该方法)的stunum和obj的stunum是否相等。equals()方法属于Object类中的方法,下面讲讲如何实现 ,先来看看源代码
Object默认是所有类的父类,默认继承,故不需要继承直接可以重写其中的equals()方法 ,下面是具体的实现方法
public class Compare {
static class Student{
String name;
int stunum;
public Student(String name,int stunum){
this.name=name;
this.stunum=stunum;
}
@Override //重写equals()方法
public boolean equals(Object o){
if(this==o){ //如果当前引用该方法的对象就是o,那么一定相等
return true;
}
if(!(o instanceof Student)){ // x instanceof y (判断x是不是y的实例)
return false;
}
Student stu=(Student) o;
if(this.stunum==stu.stunum){
return true;
}
return false;
}
}
public static void main(String[] args) {
Student x=new Student("皮卡丘",2022111);
Student y=new Student("皮卡丘",2022111);
if(x==y){
System.out.println("false");
}
if(x.equals(y)){
System.out.println("true");
}
}
}
------------------------输出true