Object--equals 灰太狼 2022-05-12 08:12 163阅读 0赞 package jave; import javax.jws.soap.SOAPBinding; /*Object--equals*/ public class Equals { 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.equals(s2));//比较两个对象的值相不相等 } } class Cat { int color; int height; int weight; public Cat (int color, int height, int weight){ this.color = color; this.height = height; this.weight = weight; } //重写equals方法 public boolean equals(Object obj) { if(obj == null) return false; else { if(obj instanceof Cat) {//instanceof 左边对象是否为instanceof 右边类的实例,返回一个boolean类型值。 Cat c = (Cat)obj; if(c.color == this.color && c.height == this.height && c.weight == this.weight ) return true; } } return false; } }
还没有评论,来说两句吧...