Java中equals()重写示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wuqingdeqing/article/details/79966838

很多时候看到许多地方说在自己的类里重写equals()方便用以比较两个对象相等,但一直未能详细探索到底怎么重写是比较好的方式。如今看到书上的一个模板,故记之。

如果该对象的引用和参数对象的引用相同,返回true。这项测试在成立时能够免去其他所有测试工作。

如果参数为null,返回false(还可以避免在之后的代码中使用空引用)。

如果两个对象的类不同,返回false。要得到一个对象的类,可以使用getClass()方法。可以使用==判断Class类型的对象是否相等,因为同一种类型的所有对象的getClass()一定能够返回相同的引用。

将参数对象的类型从Object转换到Date,因为前一项已经测试已经通过,这种转换必然成功。

如果任意实例变量的值不相同,返回false。

实例类Date如下:

public class Date {
	private final int month;
	private final int day;
	private final int year;

	public Date(int m, int d, int y) {
		month = m;
		day = d;
		year = y;
	}

	public int month() {
		return month;
	}

	public int day() {
		return day;
	}

	public int year() {
		return year;
	}

	public boolean equals(Object x) {
		if (this == x) {
			return true;
		}
		if (x == null) {
			return false;
		}
		if (this.getClass() != x.getClass()) {
			return false;
		}
		Date that = (Date) x;
		if (this.day != that.day) {
			return false;
		}
		if (this.month != that.month) {
			return false;
		}
		if (this.year != that.year) {
			return false;
		}
	}
}

关于Java中的equals重写

11-14

public class TestEquals rn public static void main(String[] args) rn Cat c1 = new Cat(1, 2, 3);rn Cat c2 = new Cat(1, 2, 3);rn System.out.println(c1 == c2);rn System.out.println(c1.equals(c2));rn System.out.println(".......................");rn rn SubCat sc1 = new SubCat(1, 2, 3, 1);rn SubCat sc2 = new SubCat(1, 2, 3, 2);rn System.out.println(sc1 == sc2);rn System.out.println(sc1.equals(sc2));rn System.out.println(".......................");rnrn System.out.println(c1.equals(sc1));rn System.out.println(".......................");//结果错误,怎样解决???rn rnrnrnclass Cat rn int color;rn int height, weight;rnrn public Cat(int color, int height, int weight) rn this.color = color;rn this.height = height;rn this.weight = weight;rn rnrn // 重写了equals方法rn public boolean equals(Object obj) rn if (obj == null)rn return false;// 判断obj对象是不是空rn else // 如果不是空,那么判断obj是不是包含Cat这个类rn if (obj instanceof Cat) rn Cat c = (Cat) obj;// 如果包含,那么把obj强制转换成Cat类rn if (c.color == this.color && c.height == this.heightrn && c.weight == this.weight) rn return true;// 方法值传递rn rn rn rn return false;rn rnrnrnrnclass SubCat extends Cat rn int age;rnrn public SubCat(int color, int height, int weight, int age) rn super(color, height, weight);rn this.age = age;rn rnrn public void display() rn System.out.println("I am the SubCat");rn rnrn // 重写了equals方法rn public boolean equals(Object obj) rn if (obj == null)rn return false;rn else rn if (obj instanceof SubCat) rn SubCat sc = (SubCat) obj;rn if (sc.color == this.color && sc.height == this.heightrn && sc.weight == this.weight && sc.age == this.age) rn return true;rn rn rn rn return false;rn rn

重写Equals()带来的困惑

09-01

最近初学C# 做练习代码如下rn[code=C#]rnusing System;rnusing System.Collections;rnusing System.Collections.Generic;rnrnnamespace test0829rn class Personrn rn public Person() rn rn rn public Person(string name) rn rn this.Name = name;rn rn public string Name get; set; rn /// rn /// 重写ToString()方法rn /// rn /// rn public override string ToString()rn rnrn return Name.ToString();rn rn /// rn /// 重写Equals()方法rn /// rn /// rn /// rn public override bool Equals(object obj)rn rn if (!(obj is Person))rn rn return false;rn rn elsern return this.Name == ((Person)obj).Name;rn rn //public override bool Equals(object obj)rn //rn // return base.Equals(obj);rn // rn public override int GetHashCode()rn rn return base.GetHashCode();rn rn rn rn class Testrn rn Person p1 = new Person("person1");rn Person p2 = new Person("person2");rn Person p3 = new Person("person1");rn Person p4 = new Person("person4");rn public void Eqtest() rn rn Console.WriteLine(p1==p3);rn Console.WriteLine(p1.Equals(p3));rn // base.Equals(p3);rn //Equals(p3);rn Console.WriteLine(Equals(p1,p3));rn //Console.WriteLine(base.ToString());rn //Console.WriteLine(Equals(p3));rn rn public void Listopt() rn rn List li = new List();rn li.Add(p1);rn li.Add(p2);rn Console.WriteLine("length= " + li.Count);rn foreach(Person p in li)rn rn Console.WriteLine(p);rn rn //li.RemoveAt(0);rn li.Remove(new Person("person1"));rn Console.WriteLine("length= "+li.Count); rn foreach (Person p in li)rn rn Console.WriteLine(p);rn rn rn public void Hashsetopt(Person p) rn rn HashSet ht = new HashSet();rn //ht.Add(p1);rn //ht.Add(p2);rn //ht.Add(p3);rn //ht.Add(p4);rn if (!ht.Contains(p))rn rn ht.Add(p);rn rn foreach(Person pe in ht)rn rn Console.WriteLine(pe);rn rn rn rnclass Programrn rn static void Main(string[] args)rn rn //new Test().hashopt();rn new Test().Listopt();rn //new Test().Eqtest();rn // new Test().Stringpot();rn //new Test().Queueopt();rn //new Test().Stackopt();rn new Test().Hashsetopt(new Person("person1"));rn new Test().Hashsetopt(new Person("person1"));rn new Test().Hashsetopt(new Person("person2"));rn rn Console.Read();rn rn rn[/code]rn如果不重写Equal()时 Li.Remove("Person1")是remove 不掉的 重写之后删掉了 ,为什么在Hashset 中却有2个person1??rnremove的时候是比较的Person.Name 为什么contains不是??rn运行结果:rnlength=2rnperson1rnperson2rnlength=1rnperson2rnrnperson1rnperson1rnperson2

关于equals和hushCode的重写!

09-25

代码如下:rnpackage pk1;rnrnpublic class TestDaternrn public static void main(String [] args)rn rn MyDate myDate = new MyDate();rn myDate.setDate(25, 9, 2011);rn myDate.getDate();rn MyDate yourDate = new MyDate();rn yourDate.setDate(25, 9, 2011);rn yourDate.getDate();rn if(yourDate.equals(myDate))rn rn System.out.println("两个对象相等!");rn rn elsern System.out.println("不相等!");rn System.out.println(myDate.hashCode());rn System.out.println(yourDate.hashCode());rn rnrnrnclass MyDaternrn private int day;rn private int month;rn private int year;rn rn public void setDate(int day,int month,int year)rn rn if(isTrueDate(day,month,year))rn rn this.day = day;rn this.month = month;rn this.year = year;rn rn elsern System.out.println("日期设置错误,请重新检查");rn rn private boolean isTrueDate(int day,int month,int year)rn rn int DateArray[][]=31,28,31,30,31,30,31,31,30,31,30,31,rn 31,29,31,30,31,30,31,31,30,31,30,31;rn if (day>0 && day<=31)rn rn if(month>0 && month<=12)rn rn if( year>0)rn rn if( isLeapYear(year))rn rn if(day<=DateArray[1][month-1])rn rn return true;rn rn elsern rn System.out.println(year+"是闰年"+month+"月-----没有"+day+"日");rn return false;rn rn rn elsern rn if(day<=DateArray[0][month-1])rn rn return true;rn rn elsern rn System.out.println(year+"年"+month+"月-----没有"+day+"日");rn return false;rn rn rn rn elsern rn System.out.println("年份必须大于零!");rn return false;rn rn rn rn elsern rn System.out.println("日期中-----没有"+month+"月");rn return false;rn rn rn elsern rn System.out.println("日期中-----没有"+day+"天");rn return false;rn rn rn rn private boolean isLeapYear(int year)rn rn if((year%4==0 && year%100!=0)|| year%400==0)rn rn return true;rn rn elsern return false;rn rn public void getDate()rn rn System.out.println(year+"年"+month+"月"+day+"日\n");rn rn public boolean equals(MyDate obj)rn rn if(this.day==obj.day && this.month==obj.month && this.year==obj.month)rn return true;rn elsern return false;rn rn public int hashCode()rn rn int result = 0;rn result=this.day; //result = this.day + this.month*100 + this.year*10000;rn return result;rn rnrn按我那个重写的hushCode不是已经覆盖了原来的hash么...返回的hashCode一样可是equals还是不想等..!!!求解rn求改!!

重写equals方法新问题

06-14

1)在使用200卡拨打电话时,如果已经输入了正确的卡号、密码,成功的登录到交换机并建立连接,则不需要再输入卡号、密码(例如在查询了电话卡中剩余金额后再拨打电话就不需要重新输入卡号、密码);如果没有建立连接,则需要输入卡号和密码。rn2)根据200卡的这一特点,编写程序实现其余额查询功能。(其它情况在符合逻辑的前提下可以假设)rn覆写object类的equals方法,实现比较信息的功能rnimport java.io.*;rnrnpublic class Card rn private String CardNum;rnrn private String CardPwd;rnrn private int CardBalance;rnrn private boolean isConnected;rnrn public Card(String CardNum, String CardPwd, int CardBalance) rn this.CardNum = CardNum;rn this.CardPwd = CardPwd;rn this.CardBalance = CardBalance;rn this.isConnected = false;rnrn rnrn public Card(String CardNum, String CardPwd) rn this.CardNum = CardNum;rn this.CardPwd = CardPwd;rn this.CardBalance = 0;rn this.isConnected = false;rnrn rnrn public String getCardNum() rn return CardNum;rn rnrn public String getCardPwd() rn return CardPwd;rn rnrn public int getCardBalance() rn return CardBalance;rn rnrn public void setisConnected(boolean isConnected) rn this.isConnected = isConnected;rn rn rn public boolean equals(Object other) rn if (other == this) rn return true;rn rn if (other == null) rn return false;rn rn if (getClass() != other.getClass()) rn return false;rn rn if (!(other instanceof Card)) rn return false;rn rn Card card = (Card) other;rn return card.CardNum == CardNum && card.CardPwd == CardPwd;rn rn public int hashCode() rn return (CardNum.hashCode() + this.CardPwd.hashCode()) * 31;rn rnrn public static void main(String args[]) throws IOException rnrn Card a = new Card("1000", "123456", 9999);rn Card b = new Card("1001", "123456", 999);rn Card c = new Card("1002", "123456", 99);rnrn String num = "";rn String password = "";rn byte buffer[] = new byte[256];rn byte buffer1[] = new byte[256];rn while (!a.isConnected && !b.isConnected && !c.isConnected) rn System.out.print("Please enter your acount:");rn int count = System.in.read(buffer);rn for (int i = 0; i < count - 2; i++) rn num += (char) buffer[i];rn rnrn System.out.print("Please enter your password:");rn int count1 = System.in.read(buffer1);rn for (int i = 0; i < count1 - 2; i++) rn password += (char) buffer1[i];rn rn /*rn * 下面写成Card temp = new Card(num, password);rn * 所有判断都不通过rn * 写成Card temp = new Card ("1000","123456")rn * 就能通过rn * 为什么rn */ rn rn Card temp = new Card(num, password);rnrn if (a.equals(temp)) rn a.setisConnected(true);rn System.out.println(a.getCardNum() + " have logined");rn System.out.println("Your account's balance is"rn + a.getCardBalance());rnrn else if (b.equals(temp)) rn b.setisConnected(true);rn System.out.println(b.getCardNum() + "Have logined");rn System.out.println("Your account's balance is "rn + b.getCardBalance());rnrn else if (c.equals(temp)) rn c.setisConnected(true);rn System.out.println(c.getCardNum() + "Have logined");rn System.out.println("Your account's balance is"rn + c.getCardBalance());rnrn rnrn rn rn rn

初学JAVA,请教一个equals重写问题

01-23

比较多,请耐心的看一下,谢谢~~rnrn我知道在Object类中equals实际比较的是两个对象是否指向同一个内存区域rn那在自己写的类中要让它只比较内容是否相等就要重写这个方法rn可是其中有一点必须使用getclass()判断所属类是否相等,在有继承的情况时还不能用instenceof判断,因为会给子类留空子转,不能让子类转空子的原因是违反了JAVA语言规定中对equals对称性的要求rn比如A是父类B是子类a,b分别是相应的对象且内容相同rn在A中重写equals时不能使用rnif (!(otherObject instanceof A)) return false;rn书上的意思似乎是a.equals(b)=ture;rn b.equals(a)!=turern那是不是B继承A后在B的equals中rnif (!(otherObject instanceof A)) return false;rn就变成了rnif (!(otherObject instanceof B)) return false; rnrn这个instanceof操作符不是判断:左面对象是不是右面的类创造的吗?rn那为什么上面那a.equals(b)=ture呢?rn子类对象也算是父类创造的吗?rnrn还有就是这个rnclass Employeern // . . .rn public boolean equals(Object otherObject)rn rn . . .rn // if the classes don't match, they can't be equalrn if (getClass() != otherObject.getClass())rn return false;rn . . .rn rnrnclass Manager extends Employeernrn . . .rn public boolean equals(Object otherObject)rn rn . . .rn if (!super.equals(otherObject)) return false;rn . . . rn rnrnrn昏迷``这里为什么又要用super.equals(otherObject)呀?rn那如果otherObject是一个Manager对象比如m, Employee的一个对象ern那e.getClass()和m.getClass()是不是相同的啊rnrn那如果不同的话,假如有Manager对象a,b(内容相同)rn那a.equals(b)返回什么呢?rn带到程序里不是这样的吗?rn执行if (!super.equals(b)) return false;rn => Employee中的 if (getClass() != b.getClass()) return false;rn那不就返回false啦??rnrn郁闷,越搅越晕,我也不知道我是否表达的够清楚,也不知道是否哪里就理解错了rn希望有明白我意思的前辈能给我详细的说明一下,rn万分感激^0^~~~~~~rn

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试