zoukankan      html  css  js  c++  java
  • JAVA基础--toString, equals方法

    ==比较的是地址

    equals比较的是内容.

    所以要重写object的equals方法.

    public class TestEquals {
    	public static void main(String[] args) {
    		Cat c1 = new Cat(1, 2, 3);
    		Cat c2 = new Cat(1, 2, 3);
    		System.out.println(c1 == c2);
    		System.out.println(c1.equals(c2));
    		
    		String s1 = new String("hello");
    		String s2 = new String("hello");
    		System.out.println(s1 == s2);
    		System.out.println(s1.equals(s2)); 
    	}
    }
    
    class Cat {
    	int color;
    	int height, weight;
    	
    	public Cat(int color, int height, int weight) {
    		this.color = color;
    		this.height = height;
    		this.weight = weight;
    	}
    	
    	public boolean equals(Object obj) {
    		if(obj == null) return false;
    		else {
    			if(obj instanceof Cat) {
    				Cat c = (Cat)obj;
    				if(c.color == this.color && c.height == this.height && c.weight == this.weight) {
    					return true;
    				}
    			}
    		}
    		
    		return false;
    	}
    	
    }
    

    结果:

    --------------------Configuration: <Default>--------------------
    false
    true
    false
    true
    

     

    如果直接输出一个对象, 会输出类名字@hashcode,

    应该重写toString方法:

    public class TestToString {
    	public static void main(String[] args) {
    		Dog d = new Dog();
    		System.out.println("d:=" + d);
    	}
    }
    
    class Dog {
    	public String toString() {
    		return "I'm a cool dog!";
    	}
    }
    

      

     

      

  • 相关阅读:
    变量提升
    前端UI框架和JS类库
    ES6---Map数据结构
    ES6---Set数据结构
    Array.from//Array.of的用法
    闭包的理解和应用场景
    vue-router 的用法
    原型链和作用域链的理解
    WordPress更换了域名 主页、文章、图片路径错误 解决办法
    wordpress 安装新的主题后启动后报错
  • 原文地址:https://www.cnblogs.com/wujixing/p/5328102.html
Copyright © 2011-2022 走看看