Java面试题----Java基础---- == 和 equals区别

== 的作用:

基本类型:比较的就是值是否相同

引用类型:比较的就是地址值是否相同

equals 的作用:

用于引用类型:默认情况下,比较的是地址值

包装类、String类中equals()被复写,比较两个字符串的内容

代码示例:

public class Main {
	public static void main(String[] arg){
	
	    //Car 未重写equals方法 Student重写了equals方法
	
	    //==示例
		System.out.println("---- == ----");
		int a = 1;
		int b = 1;
		System.out.println("基本类型比较");
		System.out.println(a==b);

		Car c1 = new Car("bmw");
		Car c2 = new Car("bmw");
		System.out.println("引用类型比较");
		System.out.println(c1==c2);


		//equals示例
		System.out.println("----equals----");
		Integer c = 2;
		Integer d = 2;
		System.out.println("包装类型比较");
		System.out.println(c.equals(d));

		String s1 = "aaaa";
		String s2 = "aaaa";
		System.out.println(s1.equals(s2));

		Car car1 = new Car("大众");
		Car car2 = new Car("大众");
		System.out.println("未重写equals的类类型比较");
		System.out.println(car1.equals(car2));

		Student student1 = new Student("名字",18);
		Student student2 = new Student("名字",18);
		System.out.println("重写了equals的类类型比较");
		System.out.println(student1.equals(student2));
	}
}

运行结果如下

---- == ----
基本类型比较
true
引用类型比较
false
----equals----
重写了equals的包装类型比较
true
true
未重写equals的类类型比较
false
重写了equals的类类型比较
true

当我们需要重新定义类型的相等概念时,就可以按照自己的相等规则来重写类的equals方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值