equals和==的区别

equals是object提供的一个方法

equals是用来比较两个基本类型的变量值是否相等,如果用在引用类型中是比较两个变量是否指向同一个对象

在object中equals和==都是比较地址是否相等,而在String中equals则是比较值是否相等

equals比较的是两个对象的内容是否相等,而==比较的是内存中的值是否相等

equals不可以用来比较整型变量

以下是代码实现:

 

//定义一个Student类
public class Student {

	private int age;
 
	public Student(int age) {
		this.age = age;
	}

	public boolean equals(Object obj) {
		if(this==obj){
			return true;
		}
		if(obj instanceof Student){
			Student st = (Student)obj;
			return this.age==st.age;
		}
		return false;

		
	}

}

 

//定义一个Demo3主类,创建对象输出他们的结果并分析其原因
public class Demo3 {
	
	public static void main(String[] args) {
		
		Student s1 = new Student(100);
		Student s2 = new Student(100);
		Student s3 = s1;
		
		System.out.println(s1==s2);
		System.out.println(s1.equals(s2));
		System.out.println(s1.equals(s3));
	}

}

 

//定义一个Demo类,分别用几种不同的方式给以下7个变量赋值,分析这几种方式有什么区别
public class Demo {

	public static void main(String[] args) {

		// 以下三种方式都是在内存中保存一个数值100

		int a1 = 100;
		int a2 = 100;

		Integer a3 = 100;
		Integer a4 = 100;

		Integer a5 = new Integer(100);
		Integer a6 = new Integer(100);

		System.out.println(a1 == a2);
		System.out.println(a3 == a4);
		System.out.println(a1 == a3);

		System.out.println(a5 == a6);
		System.out.println(a1 == a5);
		System.out.println(a3 == a5);
		
		int a7 = a6;

 

//定义一个Demo2主类,分别给变量赋值,分别用==和equals输出结果,看有什么不同并分析其原因
public class Demo2 {

	public static void main(String[] args) {

		String s1 = "ABC";
		String s2 = "ABC";

		String s3 = new String("ABC");
		String s4 = new String("ABC");

		System.out.println(s1 == s2);
		System.out.println(s3 == s4);
		System.out.println(s1 == s3);
		
		System.out.println("-------------------------");
		
		System.out.println(s1.equals(s2));
		System.out.println(s3.equals(s4));
		System.out.println(s1.equals(s3));

	}

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值