java中的equals方法与==适用范围

//【注意】:在此之前首先明确String s = "123" 和 String s = new String("123")的区别。先说String s = "123"表示在栈中创建一个变量s然后复制"123",之后如果创建String s1 = "123"时发现栈中已经有"123"了那么将s1指向这个123,也就是说此时s和s1指向的是同一个内存地址,这个可以用int hashCode = System.identityHashCode(s); int hashCode1 = System.identityHashCode(s1);看一下地址是确实相同的;再来说String s = new String("123"),如果创建完这个对象,下次创建String s1 = new String("123"),他和之前查看栈中是否有“123”不同而是直接创建一个新的对象,也就是开辟了一块儿新的内存,所以s和s1指向的是两块儿地址。

//对于==这个在学c++时就知String s = new String("123")道这是比较内存首地址的,也就是判断两个变量若内存首地址相同那么他们的值必然相同。而如果定义对象则不然,如下面代码中:String s = new String("123"); String ss = new String("123");这两个相当于是两个对象,那么此时这两个对象就是两块儿内存地址的引用,因此如果直接通过 s == ss这样比较内存首地址那肯定不同,对于这种申请字符串对象比较有equals方法,他是相当于将两块儿内存地址中的值取出来比较内容的,所以s.equals(ss)这是相同的。【注意】:在下面代码中,我们第一了实例变量a,b,c若新定义两个对象ob1, ob2那么每个对象都有三个私有属性,若项判断两个对象内容相同能否用equals呢?答案是不行的,此时要从写或者自定义一种比较方法,下面见代码:

package equals;

public class equal {

	private int a;
	private int b;
	private int c;
	
	public static void main(String[] args) {
		
		String s = new String("123");
		String ss = new String("123");
		
		if(s == ss){
			System.out.println("==can compare s and ss");
		}else{
			System.out.println("==cannot compare s and ss");
		}
		
		if(s.equals(ss)){
			System.out.println("equals can compare s and ss");
		}else{
			System.out.println("equals cannot compare s and ss");
		}
		
		equal ob1 = new equal();
		equal ob2 = new equal();
		
		equal.setP(ob1);
		equal.setP(ob2);
		
		System.out.println("ob1:" + ob1.a + " " + ob1.b + " " + ob1.c);
		System.out.println("ob2:" + ob2.a + " " + ob2.b + " " + ob2.c);
		
		if(ob1 == ob2){
			System.out.println("==can compare ob1 and ob2");
		}else{
			System.out.println("==cannot compare ob1 and ob2");
		}
		
		if(equal.equalss(ob1, ob2)){
			System.out.println("equalss can compare ob1 and ob2");
		}else{
			System.out.println("equalss cannot compare ob1 and ob2");
		}
		return ;
	}

	/**
	 * 通过调用setter和getter方法设置实例变量
	 * @return
	 */
	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	public int getC() {
		return c;
	}

	public void setC(int c) {
		this.c = c;
	}
	
	public static void setP(equal ob){	//这个方法是设置自己定义的两个对象的实例变量
		ob.setA(1);
		ob.setB(2);
		ob.setC(3);
	}
	
	
	public static boolean equalss(equal a, equal b) {	//这个方法是对两个equal对象内容是否相同写的方法
		if(a.a == b.a && a.b == b.b && a.c == b.c){
			return true;
		}else{
			return false;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/small__snail__5/article/details/81050983