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?

Similar Messages

  • How to override truncateToFit method for SuperTabNavigator

    Hi All,
               How to override truncateToFit method for SuperTabNavigator.
    we have editableLabel method for changing the tab name.
    it is dispalying the ... elipse when entered characters grater than the tab width. it is ok.
    but if the entered characters less than the tab width it is also appending the ... elipse.
    i dont want that . how to remove those. i dont want completely truncateToFit option.
    how to override .
    Can any help me regarding this?
    Thanks in Advance
    Raghu.

    Give me a sample codeNo. Read the links provided by Yannix, try it out for yourself, and if you still have a question, post the code you tried.
    db

  • 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.

  • 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.

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • How to override ExecuteWithParms method?

    How I can override ExecuteWithParms method?
    as when click on execute button there are many parameters should return result from another table
    as select query from different table, can i do this? and how??

    thanks Timo. this is more detail
    I have two table Fundemental and Emails and I have many search parameters
    so I need to make custom adf search when click on execute search, get result from all search parameters
    so i need to override executeWithParms to change return value when search in pEmail parameter
    to return "ID_NO IN (SELECT PERSON_CODE FROM EMAILS WHERE EMAIL LIKE '%" + getpEmail()  + "%')";

  • How  to override toString() method ?

    class  Test
    String x[];
    int c;
    Test(int size)
    x=new String[size];
    c=-1;
    public void addString(String str)
    x=new String
    x[++c]=str;
    public void String toString()
    //  i want to override toString method to view the strings existing in the x[]...
    //   how do i view the strings ?
    //  probabily i should NOT use println() here (..as it is inside tostring() method ..right? )
    //   so i should  RETURN   x[] as an array...but the  toString() method return  type is String not the String array!.
    //   so i am in trouble.
    so in a simple way my question is how do i override toString() method to view the Strings stored in the array ?
    i am avoiding println() bcoz of bad design.
    }

    AS you said, the toString method returns a String - this String is supposed to be a representation of the current instance of your class's state. In your case, your class's state is a String array, so you just pick a format for that and make a String that fits that format. Maybe you want it to spit out something like:
    Test[1] = "some string"
    Test[2] = "some other String"If so, code something like:public String toString() {
        StringBuffer returnValue = new StringBuffer();
        for (int i = 0; i < x.length; i++) {
            returnValue.append("Test[" + i + "] = \"" + x[i] + "\"";
        return returnValue.toString();
    } If you don't mind the formatting of the toString method that Lists get, you could just do something like:public String toString() {
        return java.util.Arrays.asList(this).toString();
    } and call it good. That will print out something like:
    [Some String, another String, null]Depending on what's in your array.
    Good Luck
    Lee

  • 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.

  • How to override Approve button for list item?

    Hello,
    Is there a way how to override the method that runs after list item is approved / rejected? I know there is a way for the Save button but I can't find how to do it for the Approve button.
    I have a list with approval and workflow. Then I have a page that displays the items from the list in my webpart in a calendar/grid way. The items in the webopart have links leading to the display form with the item ID and Source parameters. Source parameter
    leads back to this page. The background color of the item in the webpart is decided by the approval state of the item.
    When user approves the item and the item form closes user is then sent to the page with the webpart (via the Source parameter) but the workflow takes couple of seconds more to process the aproval so the color is not changed when the webpart renders but if
    the page is refreshed it shows the correct color because the workflow has finished.
    I want to override the Approval method, let it update the item so the workflow can fire and process the approval, delay the form a bit and then continue as usual so when the user is redirected to the webpart page it would render with the correct state.
    I can make a delay page that redirects to the webpart page and change the Source parameter in the items link to go there but it doesn't look that great.
    Or maybe there is a way how to do it in Javascript? I am using it in the new item form using the SP.UI.ModalDialog.showModalDialog(options) function where the dialogReturnValueCallback refreshes the windows after 3 seconds.
    dialogReturnValueCallback: function(dialogResult) {
            if (dialogResult == SP.UI.DialogResult.OK) {
             setTimeout(function(){window.location = "MyPageUrl"}, 3000)
    Thanks for any tips and ideas!

    you can try to achieve this via separate responsibility by personalizing the form by display false on the particular control button..

  • 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/...

  • 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.

  • How to override the create method invoked by a create form?

    Hello everyone, I'm using ADF Faces and have the next question:
    How can I override the create method which is invoked by a create form to preset an attribute in the new row (the preset value is not fixed, I have to send it to the method as a parameter as it is obtained using an EL expression)?
    In the ADF guide I read how to override a declarative method (Section 17.5.1 How to override a declarative method), but this explains how to do it with a method that is called by a button. I don't know how to do the same with a method which is called automatically when the page is loaded.
    I also tried overriding the view object's createRow() method to receive a parameter with the preset values but it didn't work, I believe that was because the declarative create method is not the same as the view object's createRow. This caused the form to display another row from the viewobject and not the newly created one (I also set the new row into STATUS_INITIALIZED after setting the attribute).
    Well, I hope my problem is clear enough for somebody to help me.
    Thank you!

    Hello,
    I'm not sure you can do it with standard generated Create Form.
    In your view object you'll need to create your own create method with parameters, publish it to client interface and invoke instead of standard generated create action in page definition.
    Rado

  • 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

  • How to Compare Two Strng without .equals() method

    Hiii,
    How to compare two Strings with out .equals method if there are white spaces in between these string it should be avoided..
    eg: ab cd ef g is equal to a bc de fg
    Please give me the logic or code..
    Your help will be appreciated

    dude find the code without the equal method
    public class test {     
         public static void main(String args[])
              String str = "ab cd ef g" ;
              String str1 = "a bc de fg";
              char []ch = str.toCharArray();
              char []ch1 = str1.toCharArray();
              int counter =0, counter1 = 0;
              while(counter < ch.length && counter1 < ch1.length)
                   while(ch[counter]==' ')
                        counter++;
                   while(ch1[counter1]==' ')
                        counter1++;
                   if(ch[counter] != ch1[counter1])
                        break;
                   counter++; counter1++;
              if(counter == ch.length && counter1 == ch1.length)
                   System.out.println("true");
              else
                   System.out.println("false");
    }

Maybe you are looking for

  • ECM-Problem with Change number in CS01 and CS02 Transactions

    Hi Experts, I am creating or changing BOM's using above transactions. I am entering the change number while creation and changing the BOM to track the changes.Here my problem is these transactions are not validating the ECM number. If you enter any v

  • How can I make imaginary number with known real number

    I need to compose pure imeginary number in my programming(ie. chamge the real number to be the imeginary part of a complex number). But The functions I found can only change the real number to be the real part of a ccomplex number. How can I compose

  • Dynamic link question

    I have cs4 and when I create a link between after effects and premiere I can import the project, but it just plays a black screen with no audio either. when I check out the properties the imported project looks seems ok it doesn't work bringing in pr

  • Oracle WebDB for Linux

    Is there a place we can download Oracle WebDB for Linux? Thanks in advance. Zhenhua null

  • Warehouse Mgmt Scan guns

    We are using warehouse management and using the scan guns to do the warehouse transactions. we have recently changed to the ITS technology for our mobile devices. . The issue is that now it is comparatively longer to complete the transactions. We hav