zoukankan      html  css  js  c++  java
  • [Java] 类的Equals方法 (String, Data类都已经自动重写)

    package com.bjsxt.chap03;
    
    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 weight, height;
        public Cat(int color, int weight, int height) {
            this.color = color;
            this.weight = weight;
            this.height = height;
        }
        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;
        }
    }
    

    Output

    false

    true

    false

    true

  • 相关阅读:
    switch语句
    switch语句
    if语句三种格式
    dowhile语句
    if语句三种格式
    if语句配对
    ansible
    linux系统中网站服务程序(web服务/httpd服务)
    ansible
    ansible
  • 原文地址:https://www.cnblogs.com/robbychan/p/3786911.html
Copyright © 2011-2022 走看看