简体   繁体   中英

Override equals

I have this class:

public class Phone{ 
    private String number;
    //get and set of class
}

Then i have another class that uses the "Phone"

public class Antena{
   private String name;
   private ArrayList<Phone> phones;
}

Now before add an element i would like only add if the element don't exist in the array. I'm new in Java and after some research i have found that i need to override the equals method. So can anyone give me some hints please?

This is how i use the equals method:

if(!phones.equals(phone))
   phones.add(phone);

The comments now have enough information to actually answer the question.

Part 1

Implement equals:

public boolean equals(Object obj) { 
  if (obj == null) return false;
  if (obj.getClass() != this.getClass()) return false;
  Phone t = (Phone ) obj; 
  return t.number.equals(this.number);
}

Part 2

Implement hash code

public int hashCode() {
  return number.hashCode();
}

Part 3

Use a set instead of an ArrayList to require uniqueness..

private HashSet<Phone> phones;

You override equals method to do equality test of the class objects. For example you have two Phone objects p1 and p2.

Phone p1 = new Phone();
Phone p2 = new Phone();
p1.setNumber(10);
p2.setNumber(10);
\\Ideally these two objects are equal but when you try to do equality test , it will return false.
System.out.println(p1==p2);  // outputs false because p1 and p2 are two different references 

holding different memory addresses. Also ,

System.out.println(p1.equals(p2));  // prints false when not overrided 

When you override equals method you can add a criteria to logically test these two objects.

public boolean equals(Object obj)
  {

    if (!(obj instanceof Phone)) 
      return false;
    return this.getNumber() == ((Phone)obj).getNumber();
  }

Now if you call equals method on p1 and p2 objects , it will return true. Equals method test is useful when you want to equate two class objects on basis of instance variables and not reference addresses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM