Overriding equal() method

Hi all,
I am new to this forum.This is my first post.
Please see below code...
class One
  private int a,b;        //we override equal() method  in this class
public One(int x,int y)
   a=x;
   b=y;
public boolean equals(Object o)
     if((o instanceof One )&&(((One)o).getAValue()==this.a)&&(((One)o).getBValue()==this.b))+
        return true;
     else
        return false;
public class ToCheckEqalityOfObjects4
public static void main(String[] args)
    One ob1=new One(2,4);
    One ob2=new One(2,4);
    One ob3=new One(6,12);
    One ob4=ob3;
    if(ob1==ob2)
      System.out.println("ob1==ob2 TRUE");
    else
      System.out.println("ob1==ob2 FALSE");
    if(ob1.equals(ob2))
      System.out.println("ob1.equals(ob2) TRUE");
    else
      System.out.println("ob1.equals(ob2) FALSE");
    if(ob4==ob3)
      System.out.println("ob4==ob3 TRUE");
    else
      System.out.println("ob4==ob3 FALSE");
    if(ob1.equals(ob3))
      System.out.println("ob4.equals(ob3) TRUE");
    else
      System.out.println("ob4.equals(ob3) FALSE");
}While compiling this code i got a error like..
E:\WINDOWS\java\IOStreams\ToCheckEqalityOfObjects4.java:23: cannot find symbol
symbol  : method getAValue()
location: class IOStreams.One
     if((o instanceof One )&&(((One)o).getAValue()==this.a)&&(((One)o).getBValue()==this.b))
E:\WINDOWS\java\IOStreams\ToCheckEqalityOfObjects4.java:23: cannot find symbol
symbol  : method getBValue()
location: class IOStreams.One
     if((o instanceof One )&&(((One)o).getAValue()==this.a)&&(((One)o).getBValue()==this.b))
2 errorsWhat's wrong with my code ?
Please tell me..
Thankq very much for reading this.

The error message tells you exactly what's wrong. You're calling methods that you didn't actually define.

Similar Messages

  • How to override equals method

    The equals method accepts Object as the parameter. When overriding this method we need to downcast the parameter object to the specific. The downcast is not the good idea as it is not the OO. So can anyone please tell me how can we override the equals method without downcasting the parameter object. Thank you.

    For comparing the objects by value overriding the equals method what I did is like this
    public boolean equals(Object o){
        if( o instanceof Book){
            Book b = (Book)o;
            if(this.id == b.id)
                return true;
        return false;
    }But in the above code I have to downcast the object o to the class Book. This downcasting is not a good as it is not Object-Oriented. So what I want to do is avoid the downcasting. So any idea how to do it?

  • Need help overriding equals() method

    Hi I have an assignment where I have to override the equals() method, the thing that's bugging me though is my instructor says the parameter has to be Object. I understand you can pass anything through Object but if I want to get a method from the object I passed through how would I go about that? What I'm basically trying to do is compare two arrays of numbers and see if both array sizes are the same and both have the same values at each corresponding index.
    - Chris

    The issue here is that the signature of this equals method must match that of that which it is overriding, or in other words, it must match the equals method of Object. So it must take an object parameter. Here I would use the instanceof(...) method to see if the object matches what I want, if not, then return false, if so, cast the object as your specific object and call methods to my heart's content.

  • When we override Hashcode and Equal Methods

    Hi....I have doubt regading Hashcode and equal methods
    why we override this two methods....
    why we override hashcode method when we are overriding equal method,
    i would very thankful to give answser
    Thank you
    Ramesh

    hash code is computed to check the equality of two
    objects ,
    that is why if u change the default equal method
    implementation , u need to change the hashcode method
    as well.That's an incomplete answer at best.
    The hashcode method is used by hashing algorithms and data strcutures such as HashMap. This value is used to determine what 'bucket' the reference will go into. It cannot, by itself determine equality.
    If you are still unsure, I suggest looking up 'hash table' on google. I'm sure there's a decent explanation on wikipedia.

  • Overriding hashcode method

    Can u pls tell me friends why should definetly i override the hashcode method if i override equals method of the Object class

    Because the contracts of equals and hashCode are strongly bound to each other.
    For each objects x and y where x.equals(y) returns true x.hashCode() must be equal to y.hashCode().
    If you don't follow this convention you'll get hard-to-find bugs as soon as you use your object as a key in some kind of HashMap/HashTable/...

  • Why do we need to override Hascode and Equals method?

    Hi,
    == checks if the two references are equal and .equlas will check if the value is same, if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).
    Please someone elaborate on this and also tell me what role hashcode plays in this.
    thanks
    Anirudh

    anirudh1983 wrote:
    if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).Many equals() methods do run an '==' check first for efficiency (and I would recommend it if you're writing one yourself).
    Please someone elaborate on this and also tell me what role hashcode plays in this.The reason that it is good practise to override equals() and hashCode() together is to maintain consistency.
    Hashcodes are used by all Java collections that contain the word 'Hash' in their name, and may also be used by other programs that need a hash code for identification; so if you supply one, you must follow the rules (which you can find in the API for Object.equals() and Object.hashCode()).
    The main rule is this: *objects that are equal() must have equal hashcodes*.
    Note that the reverse is NOT true: objects that are not equal() do not have to have different hashcodes, but it is usually better if they do.
    There is quite a lot to know about hashcodes, and what makes a good one, so I suggest you follow dcminter's advice if you want to be a happy and prosperous Java programmer.
    Winston

  • Overriding equals(Object o) method

    hi,
    I have a problem in equals method ..returns true always...
    can anyone suggest whats wrong ?
    thanks for the help
    public  boolean equals(Object NumberC)
                if (NumberC == null) return false;
                 if ( NumberC instanceof Counter)
                      Counter myCr = ( Counter) NumberC;
                     if(this.number == (myCr)
                         return true;
                     }//end if
                 } //end if 
                 return false;
             }// end equals
      

    sorry..yes it always returns true
    here's my code again
    public  boolean equals(Object NumberCounter)
                if (NumberCounter == null) return false;
                 if ( NumberCounter instanceof Counter )
                     Counter myCr = ( Counter ) NumberCounter;
                     if(this.number == (myCr.number))
                         return true;
                     }//end if
                 } //end if 
                 return false;
             }// end equals

  • ...is not abstract and does not override abstract method compare

    Why am I getting the above compile error when I am very clearly overriding abstract method compare (ditto abstract method compareTo)? Here is my code -- which was presented 1.5 code and I'm trying to retrofit to 1.4 -- followed by the complete compile time error. Thanks in advance for your help (even though I'm sure this is an easy question for you experts):
    import java.util.*;
       This program sorts a set of item by comparing
       their descriptions.
    public class TreeSetTest
       public static void main(String[] args)
          SortedSet parts = new TreeSet();
          parts.add(new Item("Toaster", 1234));
          parts.add(new Item("Widget", 4562));
          parts.add(new Item("Modem", 9912));
          System.out.println(parts);
          SortedSet sortByDescription = new TreeSet(new
             Comparator()
                public int compare(Item a, Item b)   // LINE CAUSING THE ERROR
                   String descrA = a.getDescription();
                   String descrB = b.getDescription();
                   return descrA.compareTo(descrB);
          sortByDescription.addAll(parts);
          System.out.println(sortByDescription);
       An item with a description and a part number.
    class Item implements Comparable     
          Constructs an item.
          @param aDescription the item's description
          @param aPartNumber the item's part number
       public Item(String aDescription, int aPartNumber)
          description = aDescription;
          partNumber = aPartNumber;
          Gets the description of this item.
          @return the description
       public String getDescription()
          return description;
       public String toString()
          return "[descripion=" + description
             + ", partNumber=" + partNumber + "]";
       public boolean equals(Object otherObject)
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)
             && partNumber == other.partNumber;
       public int hashCode()
          return 13 * description.hashCode() + 17 * partNumber;
       public int compareTo(Item other)   // OTHER LINE CAUSING THE ERROR
          return partNumber - other.partNumber;
       private String description;
       private int partNumber;
    }Compiler error:
    TreeSetTest.java:25: <anonymous TreeSetTest$1> is not abstract and does not over
    ride abstract method compare(java.lang.Object,java.lang.Object) in java.util.Com
    parator
                public int compare(Item a, Item b)
                           ^
    TreeSetTest.java:41: Item is not abstract and does not override abstract method
    compareTo(java.lang.Object) in java.lang.Comparable
    class Item implements Comparable
    ^
    2 errors

    According to the book I'm reading, if you merely take
    out the generic from the code, it should compile and
    run in v1.4 (assuming, of course, that the class
    exists in 1.4). I don't know what book you are reading but that's certainly incorrect or incomplete at least. I've manually retrofitted code to 1.4, and you'll be inserting casts as well as replacing type references with Object (or the erased type, to be more precise).
    These interfaces do exist in 1.4, and
    without the generics.Exactly. Which means compareTo takes an Object, and you should change your overriding method accordingly.
    But this raises a new question: how does my 1.4
    compiler know anything about generics? It doesn't and it can't. As the compiler is telling you, those interfaces expect Object. Think about it, you want to implement one interface which declares a method argument type of Object, in several classes, each with a different type. Obviously all of those are not valid overrides.

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • Problem in not overriding equals and Hashcode

    I have a very small question. We know that if we do not override the equals and hascode of Object class, we can not use the object in the Hashed collection. Can anybody provide me a concrete example which indicates the problem if we do not override the equals and hascode.

    back to the original question from DebadattaMishra
    I have a very small question. We know that if we do
    not override the equals and hascode of Object class,
    we can not use the object in the Hashed collection.
    Can anybody provide me a concrete example which
    indicates the problem if we do not override the
    equals and hascode.lets extend the example from jverd. Suppose we have a Person and want to store some Score in a HashMapclass Person {
        String name;
        Person(String name) {
            this.name = name;
    class Score {
        int value;
        Score(int value) {
            this.value = value;
    public class PersonTest {
        Map<Person, Score> map = new HashMap<Person, Score>();
        void test() {
            map.put(new Person("John"), new Score(1));
            map.put(new Person("Maria"), new Score(2));
            Score score = searchScore("John");
            System.out.println("Found: " + score);  // Found: null
        Score searchScore(String name) {
            return map.get(new Person(name));
    }if you run test() you will get "Found: null" since the John instance in the HashMap is not the same as used in searchScore. HashMap uses the equals method from Object since we have not overridden it.
    If we add an equals methodclass Person {
        String name;
        Person(String name) {
            this.name = name;
        public boolean equals(Object obj) {
            if(obj instanceof Person) {
                Person p = (Person) obj;
                return name.equals(p.name);
            } else {
                return false;
        // hashcode not overridden
    }we probably will get "Found: null" most if the time. The HashMap uses the hashcode() to create an index for saving the keys, so it mostly will not find the Person.((there is still a very small probability that the correct Person is found))
    It will work fine if we add a hashcode like    public int hashCode() {
            return name.hashCode();
        }I hope this example helped.

  • Adding Objects To a HashSet, overriding equals and hashCode

    Hi everyone,
    I'm trying to add objects to a HashSet, using a string identifier (an attribute of these objects) to determine if two objects are equal.
    I have a class 'IntExpEvent' class that overrides the equals and hashCode methods.
    public class IntExpEvent implements ExperimentalEvent{
    public int correctAnswer;
    public String identifier;
    public IntExpEvent(String id, int correctAnswer){
         this.identifier = id;
         this.correctAnswer=correctAnswer;
    public String getID(){
         return(this.identifier);
    public boolean equals(ExperimentalEvent e){
         return (this.identifier.equals(e.getID()));
    public int hashCode(){
         System.out.println((this.getID()).hashCode());
         return (this.getID()).hashCode();
    private int hashCode=-1;
    public int hashCode() {
         if(hashCode==-1) {
         char[] ca=getID().toCharArray();
         for(int x=0;x<ca.length;x++) {
              hashCode+=ca[x];
         return(hashCode);
         IntExpEvent e1 = new IntExpEvent("test_IntExpEvent",4);
         IntExpEvent e2 = new IntExpEvent("test_IntExpEvent",6);
         HashSet hs = new HashSet();
         System.out.println(hs.add(e1));
         System.out.println(hs.add(e2));
    I can still add both e1 and e2 to the HashSet, which is what I'm trying to stop from happening. i.e. objects with the same identifier should be treated as the same object, allowing only one to be added to the HashSet. Does anyone know how I can do this? Help would be greatly appreciated

    In fact you don't override the equals method. The signature defined in the Object class is
      boolean equals(Object o)In your case it is
      boolean equals(ExperimentalEvent e)So instead of overriding the method you're overloading it.
    Regards

  • Help need to know hashcode() and Equals method

    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........

    jverd wrote:
    euph wrote:
    jverd wrote:
    euph wrote:
    REFTY5_ wrote:
    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
    To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted.

  • Why StringBuffer does not override equals()

    Is there any reason for StringBuffer to don't override equals()
    Wargo

    Not that I can think of. I'd expect two StringBuffer instances to be considered equivalent (equal) if they both would hand me equivalent results from their toString() methods. Instead, I guess someone at Sun decided that identity was preferable to equivalence for this class's equals() method.

  • What is hash code in Java and how it is related to equals method

    Can any body give me the detailed information about hashcode and the relationship between equals method and hash code.

    Objects in Java have hash codes associated with them. An object's hash code is a signed number that identifies the object (for example, an instance of the parent class). An object's hash code may be obtained by using the object's hashCode() method as follows:
    int hashCode = SomeObject.hashCode();
    The method hashCode() is defined in the Object class and is inherited by all Java objects. The following code snippet shows how the hash codes of two objects relate to the corresponding equals() method:
    1. // Compare objects and then compare their hash codes
    2. if (object1.equals(object2)
    3. System.out.println("hash code 1 = " + object1.hashCode() +
    4. ", hashcode 2 = " + object2.hashCode());
    5.
    6. // Compare hash codes and then compare objects
    7. if (object1.hashCode() == object2.hashCode())
    8. {
    9. if (object1.equals(object2))
    10. System.out.println"object1 equals object2");
    11. else
    12. System.out.println"object1 does not equal object2");
    13. }
    In lines 3-4, the value of the two hash codes will always be the same. However, the program may go through line 10 or line 12 in the code. Just because an object's reference equals another object's reference (remember that the equals() method compares object references by default), it does not necessarily mean that the hash codes also match.
    The hashCode() method may be overridden by subclasses. Overriding the hash code will allow you to associate your own hash key with the object.

  • Need help!! How to use super in equals() method and makeCopy() method?

    This is my Name class:
    class Name {
        private String title;
        private String name;
        public Name(){
             title=" ";
             name=" ";
        public Name(String title){
             setTitle(title);
             name=" ";
        public Name(String title,String name){
             setTitle(title);
             setName(name);
        public void setTitle(String title){
             this.title=title;
        public String getTitle(){
             return title;
        public void setName(String name){
             this.name=name;
        public String getName(){
             return name;
        }   This is my Person Class
    class Person extends Name{
        private String address;
        private String tel;
        private String email;     
        public Person(){
             super();
             address=" ";
             tel=" ";
             email=" ";
        public Person(String name){
             super(name);
             address=" ";
             tel=" ";
             email=" ";
        public Person(String title,String name,String addressStr){
             super(title,name);
             setAddress(addressStr);
             tel=" ";
             email=" ";
        public Person(String title,String name,String addressStr,String phoneNum){
             super(title,name);
             setAddress(addressStr);
             setTel(phoneNum);
             email=" ";
        public Person(String title,String name,String addressStr,String phoneNum,String emailStr){
             super(title,name);
             setAddress(addressStr);
             setTel(phoneNum);
             setEmail(emailStr);
        public void setAddress(String add){
             address=add;
        public String getAddress(){
             return address;
        public void setTel(String telephone){
             tel=telephone;
        public String getTel(){
             return tel;
        public void setEmail(String emailAdd){
             email=emailAdd;
        public String getEmail(){
             return email;
         public boolean equals(Person inputRecords){
             boolean equalOrNot=false;
             if(inputRecords.super(getTitle()).equals(title))         //this is wrong
                  if(inputRecords.super(getName()).equals(name))           //this is wrong
                       if(inputRecords.getAddress().equals(address))
                            if(inputRecords.getTel().equals(tel))
                                 if(inputRecords.getEmail().equals(email))
                                      equalOrNot=true;
             return equalOrNot;   
            public void makeCopy(Person copyInto){
                 copyInto.super(setTitle(title));             //this is wrong
                 copyInto.super(setName(name));           //this is wrong
                 copyInto.setAddress(address);
                 copyInto.setTel(tel);
                 copyInto.setEmail(email);
    }How can I correct the wrong part?
    I don't understand how to use super in equals() method and makeCopy() method.

    Try something like this ...
    public boolean equals(Object other) {
      if (other==null || !(other instanceof Person)) return false;
      Person that = (Person) other;
      return getTitle().equals(that.getTitle())
          && getName().equals(that.getName())
          && getAddress().equals(that.getAddress())
          && getTel().equals(that.getTel())
          && getEmail().equals(that.getEmail())
    Notes:
    * This overrides Object's public boolean equals(Object other), which is (probably) what you meant.
    * You don't need to call "super.getWhatever" explicitly... just call "getWhatever" and let java workout where it's defined... this is better because if you then override getTitle() for example you don't need to change your equals method (which you would otherwise probably forget to do, which would probably have some interesting side effects.
    Cheers. Keith.

Maybe you are looking for

  • My macbook air takes a very long time to start how can I fix this?

    It was fine when I turned it off and the next day when I was starting my computer it took for ever. How can this be fixed. I didn't install anything or made any changes.

  • Compatibility between MSI i7 boards and Corsair DDR3 RAM kits?

    Similar issues from other posters: Thread 1, Thread 2 Are there any known compatibility issues between MSI's Intel i7 boards and Corsair's 1600 DDR3 triple-channel kits? My brother's machine (which has been discussed here before last time I tried to

  • Internet explorer 11 in modern mode has some issues in files's downloads

    I describe my problem. By using Internet Explorer 11 in modern mode, when a download begins, happening a strange issue: the name of the file is changed, this means that the "." of the extension is changed in a "_", and if presents, also the "." in th

  • Since install PE12 I cannot open raw files by default

    When I double click on a raw file to open, it opens in PE11 by default instead of newly installed PE12.  If I right click on any image file to select OPEN WITH PE11 shows by default.  I have added PE12 however, when I select it to OPEN WITH, PE12 lau

  • FME 3 Keeps crashing

    Hi, when im using fme 3 to stream, it works for a while, then suddenly it will just crash, it would show a black video output, i would then close it and it would then say that my capture card is in use, when it isnt. please help!!