Equals methods

i'm trying to get the hang of some of the equals methods and i just want to check i'm doing this right
my question is about the variables that are of type Object.(ob1, ob2)
String s1 = "water", s2 = "mountain";
Object ob1 = new String("mountain");
     Object ob2 = new Integer(250);
System.out.println("ob1.equals(s2): "+ob1.equals(s2));
System.out.println("ob2.equals(new Integer(250)): "+ob2.equals(new Integer(250)));
System.out.println("ob2.equals(new Integer(150)): "+ob2.equals(new Integer(150)));
    is it correct that even though ob1 is of type object, it is still calling the equals method of the String class, and not the the equals method of class Object?
and ob2 is pointing to an Integer object, so the Integer class equals methos gets called?
i think this is correct but not 100% sure.

jverd wrote:
mark_8206 wrote:
is it correct that even though ob1 is of type object, it is still calling the equals method of the String class, and not the the equals method of class Object?
and ob2 is pointing to an Integer object, so the Integer class equals methos gets called?Correct.thanks!

Similar Messages

  • My Equal method is not working in array person!!! help me pls

    My assignment is to create an application program that declares an array of 100 components of type person. add a person into the array and (CHECK DUPLICATE ENTRIES ARE NOT ALLOWED)
    my code is(this is in another class):
    public Boolean equals(Person p1){
              return(name == p1.name&&address == p1.address&&telephoneNo == p1.telephoneNo&&email == p1.email);
    Become(this is in my main class):
    public static boolean isEquals(Person p1)
              if(Person.getPersonCount()==1)
                   return false;
              for(int i=0;i<Person.getPersonCount()-1;i++)
                   if(p1.equals(p))
                        return true;
              return false;
    my output code is:
    public static void addPerson()
              String name, address, telephoneNo, email;
              int count=Person.getPersonCount();
              int numberPerson = Integer.parseInt(JOptionPane.showInputDialog(null,
                   "Enter number of person you want to add in (1 to 100):","Person Adding Table",
                   JOptionPane.QUESTION_MESSAGE));
              for(int i=0;i<numberPerson;i++)
                   name = JOptionPane.showInputDialog(null,"Please enter a person name:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
                   address = JOptionPane.showInputDialog(null,"Please enter a person address:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
                   telephoneNo = JOptionPane.showInputDialog(null,"Please enter a person telephone number:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
                   email = JOptionPane.showInputDialog(null,"Please enter a person email address:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
                   p[i+count]=new Person(name,address,telephoneNo,email);
                   if(isEquals(p[i+count]))
                        System.out.println("Please take note! Your person details have duplicate data...");
              System.out.println("You has added "+numberPerson+" details of person!!!");

    Don't compare Strings with ==. Use the equals() method.
    if (string1.equals(string2))Using == checks if they are the exact same object (think of it as the same location in memory). The equals() method checks if their contents are equal...just like you're trying to set up for your Person class. You want to see if the various fields of a Person object are the same...not if they are in fact the same object.

  • Several different equals methods

    Hi,
    I want to compare two different sets with eachother. The Set contains objects with a number of strings and Integers, and some of these need to be equal in order to find a match between the two different Sets. This differs from the "natural order" or the actual equal-value for the two objects, so I don�t want to implement Comparable and use the equals method directly in my Objects since I do not wat to mess with the "truth".
    I tried to used Comparator, but the equals(Object obj) method only provides one of the two objects I need to compare, and the compare(Object obj1, Object obj2) is good, but should I use it to compare two objects from two DIFFERENT Collections. It seems the compare method is mostly used for sorting, and I don�t care about sorting at this point.
    Set<MyObject> set1;
    Set<MyObject> set2;
    //compare all the objects in set 1 to all objects in set2 AND, if there is a match do:
    myObjectFromSet1.setACertainValue(myObjectFromSet2.getACertainValue);The "ACertainValue" is of course not included in the comparison, since in set1, all the "ACertainValues" are empty, but I need to pick the value from its "equal" object from set2.

    I compare them field by field in my object - strings
    and Integers - (except for one field : position).
    All must match to call them "equal". Then I want to
    set that field (position) in the set that doesn�'t
    have that info yet and pick the value from the other
    set (where there is ONE corresponding Object
    available only). After this the two objects from each
    set are "really equal".
    There might be objects available without a match, but
    those I will handle seperately.
    Thanks for taking you time, it is really appriciated.No problem. I think I understand what you mean, here's yet another little demo:import java.util.*;
    public class Main {
        public static void main(String[] args) {
            MyObject[] array1 = {new MyObject(1, "A", new Integer(11)),
                                 new MyObject(2, "B", new Integer(22)),
                                 new MyObject(3, "C", new Integer(33))};
            Set<MyObject> set1 = new HashSet<MyObject>(Arrays.asList(array1));
            MyObject[] array2 = {new MyObject(1, "A"),
                                 new MyObject(2, "B"),
                                 new MyObject(3, "C")};
            Set<MyObject> set2 = new HashSet<MyObject>(Arrays.asList(array2));
            System.out.println("Before\nset1 : "+set1);
            System.out.println("set2 : "+set2);
            List<MyObject> list1 = new ArrayList<MyObject>(set1);
            for(MyObject mo2 : set2) {
                int index = list1.indexOf(mo2);
                if(index != -1) {
                    MyObject mo1 = list1.get(index);
                    if(mo2.position == null) {
                        mo2.position = mo1.position;
                    } else {
                        mo1.position = mo2.position;
            System.out.println("\nAfter\nset1 : "+set1);
            System.out.println("set2 : "+set2);
    class MyObject {
        protected Integer id, position;
        protected String str;
        public MyObject(int id, String str) {
            this(id, str, null);
        public MyObject(int id, String str, Integer position) {
            this.id = id;
            this.str = str;
            this.position = position;
        public boolean equals(Object o) {
            MyObject that = (MyObject)o;
            return this.id == that.id && this.str.equals(that.str);
        public int hashCode() {
            return (31*this.id) ^ (37*this.str.hashCode());
        public String toString() {
            return "{id="+this.id+", str="+this.str+", position="+this.position+"}";
    }Produces the following output:Before
    set1 : [{id=3, str=C, position=33}, {id=2, str=B, position=22}, {id=1, str=A, position=11}]
    set2 : [{id=3, str=C, position=null}, {id=2, str=B, position=null}, {id=1, str=A, position=null}]
    After
    set1 : [{id=3, str=C, position=33}, {id=2, str=B, position=22}, {id=1, str=A, position=11}]
    set2 : [{id=3, str=C, position=33}, {id=2, str=B, position=22}, {id=1, str=A, position=11}]

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

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

  • Can we use equals method in JSTL

    hia all,
    is there is possible to use equals method in JSTL c:when tag. if so please give me an example or else please tell me some solution.
    regards
    subramanian

    Have you tried it anyway? Where exactly are you talking about with "contents"?
    Remember that the == operator in JSTL isn't the same as the == operator in Java. In JSTL it invokes the Object#equals() method behind the scenes, while in Java it checks the equality of the reference.

  • Difference between Object equals() method and ==

    Hi,
    Any one help me to clarify my confusion.
    stud s=new stud();
    stud s1=new stud();
    System.out.println("Equals======>"+s.equals(s1));
    System.out.println("== --------->"+(s==s1));
    Result:
    Equals ======> false
    == ------------> false
    Can you please explain what is the difference between equals method in Object class and == operator.
    In which situation we use Object equals() method and == operator.
    Regards,
    Saravanan.K

    corlettk wrote:
    I'm not sure, but I suspect that the later Java compilers might actually generate the same byte code for both versions, i.e. I suspect the compiler has gotten smart enough to devine that && other!=null is a no-op and ignore it... Please could could someone who understands bytecode confirm or repudiate my guess?Don't need deep understanding of bytecode
    Without !=null
    C:>javap -v SomeClass
    Compiled from "SomeClass.java"
    class SomeClass extends java.lang.Object
      SourceFile: "SomeClass.java"
      minor version: 0
      major version: 49
      Constant pool:
    const #1 = Method       #4.#15; //  java/lang/Object."<init>":()V
    const #2 = class        #16;    //  SomeClass
    const #3 = Field        #2.#17; //  SomeClass.field:Ljava/lang/Object;
    const #4 = class        #18;    //  java/lang/Object
    const #5 = Asciz        field;
    const #6 = Asciz        Ljava/lang/Object;;
    const #7 = Asciz        <init>;
    const #8 = Asciz        ()V;
    const #9 = Asciz        Code;
    const #10 = Asciz       LineNumberTable;
    const #11 = Asciz       equals;
    const #12 = Asciz       (Ljava/lang/Object;)Z;
    const #13 = Asciz       SourceFile;
    const #14 = Asciz       SomeClass.java;
    const #15 = NameAndType #7:#8;//  "<init>":()V
    const #16 = Asciz       SomeClass;
    const #17 = NameAndType #5:#6;//  field:Ljava/lang/Object;
    const #18 = Asciz       java/lang/Object;
    SomeClass();
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    public boolean equals(java.lang.Object);
      Code:
       Stack=2, Locals=2, Args_size=2
       0:   aload_1
       1:   instanceof      #2; //class SomeClass
       4:   ifeq    25
       7:   aload_1
       8:   checkcast       #2; //class SomeClass
       11:  getfield        #3; //Field field:Ljava/lang/Object;
       14:  aload_0
       15:  getfield        #3; //Field field:Ljava/lang/Object;
       18:  if_acmpne       25
       21:  iconst_1
       22:  goto    26
       25:  iconst_0
       26:  ireturn
      LineNumberTable:
       line 6: 0
    }With !=null
    C:>javap -v SomeClass
    Compiled from "SomeClass.java"
    class SomeClass extends java.lang.Object
      SourceFile: "SomeClass.java"
      minor version: 0
      major version: 49
      Constant pool:
    const #1 = Method       #4.#15; //  java/lang/Object."<init>":()V
    const #2 = class        #16;    //  SomeClass
    const #3 = Field        #2.#17; //  SomeClass.field:Ljava/lang/Object;
    const #4 = class        #18;    //  java/lang/Object
    const #5 = Asciz        field;
    const #6 = Asciz        Ljava/lang/Object;;
    const #7 = Asciz        <init>;
    const #8 = Asciz        ()V;
    const #9 = Asciz        Code;
    const #10 = Asciz       LineNumberTable;
    const #11 = Asciz       equals;
    const #12 = Asciz       (Ljava/lang/Object;)Z;
    const #13 = Asciz       SourceFile;
    const #14 = Asciz       SomeClass.java;
    const #15 = NameAndType #7:#8;//  "<init>":()V
    const #16 = Asciz       SomeClass;
    const #17 = NameAndType #5:#6;//  field:Ljava/lang/Object;
    const #18 = Asciz       java/lang/Object;
    SomeClass();
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    public boolean equals(java.lang.Object);
      Code:
       Stack=2, Locals=2, Args_size=2
       0:   aload_1
       1:   instanceof      #2; //class SomeClass
       4:   ifeq    29
       7:   aload_1
       8:   ifnull  29
       11:  aload_1
       12:  checkcast       #2; //class SomeClass
       15:  getfield        #3; //Field field:Ljava/lang/Object;
       18:  aload_0
       19:  getfield        #3; //Field field:Ljava/lang/Object;
       22:  if_acmpne       29
       25:  iconst_1
       26:  goto    30
       29:  iconst_0
       30:  ireturn
      LineNumberTable:
       line 6: 0
    }

  • 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

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

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

  • Scenario in which implement or Write our own hascode and equals method

    Dear All,
    Please let me know in which circumstances we write our own Hashcode method and equals method not the default one provided by java.Kindly give me complete code and scenario.
    Thanks
    Sumit

    Thanks for your reply
    I have one more question.
    When equal method of Object class give the same result as equals we override then why should we override equals.For example see the below code
    public class EqualsTest{
    public EqualsTest() {
         super();
    public static void main(String[] args) {
    Moof one =new Moof(8);
    Moof two =new Moof(8);
    if(one.equals(two))
    System.out.println("one is equals to two");
    class Moof {
    private int moofvalue;
    Moof(int val){
    System.out.println("val inside moof constructor"+val);
    moofvalue=val;
    System.out.println("moofvalue inside moof constructor" +moofvalue);
    public int getMoofValue()
    System.out.println("moofvalue inside getmoffvalue method "+moofvalue);
    return moofvalue;
    public boolean equals(Object o)
    System.out.println("Object o in equals"+o);
    if( (o instanceof Moof) &&(( (Moof)o).getMoofValue()==this.moofvalue))
    System.out.println("true");
    return true;
    else
    System.out.println("false");
    return false;
    Here the output we get is :
    val inside moof constructor8
    moofvalue inside moof constructor8
    val inside moof constructor8
    moofvalue inside moof constructor8
    Object o in equalsMoof@119c082
    moofvalue inside getmoffvalue method 8
    true
    one is equals to two
    The last output "one is equals to two" gives the same result as overridng equals by us.So why should we override equals here.
    Thanks
    Sumit

  • String equal method Vs Object equal method.

    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.

    RGEO wrote:
    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.Because "equal" means different things for different objects. For a String, "equal" would mean that both Strings being compared have the exact same characters, in the same sequence. For an Integer, "equals" would mean that both objects have the same integer value.

  • 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");
    }

  • Using equals method with an array?

    Hello all,
    I am attempting to use the equals method with an array and keep getting compiling errors. Could you please take a look at my code and tell me where I am going wrong:
    if(board[row][col].equals(" "))
              str=str + " ";
              else
              str=str + board[row][col];
    Thank you.

    Hello all,
    I am attempting to use the equals method with an
    array and keep getting compiling errors. Could you
    please take a look at my code and tell me where I am
    going wrong:
    if(board[row][col].equals(" "))
              str=str + " ";
              else
              str=str + board[row][col];
    Thank you.If you could post more of your code, that would be quite helpful...

Maybe you are looking for

  • Null representation in xml

    Hi All, I have to represent a datatbase value 'null' in xml. I use a thirdparty api(propreitary, not well know and which I have no control) for conversion and null is representaed in xml as &#0; Is this correct? But while parsing the xml data i get i

  • Adobe Illustrator quit unexpectedly

    have recently installed creative suite 3 but every time i click on illustrator or try and print, nothing happens except for Adobe Illustrator has quit unexpectedly. help

  • Mail 3.6 hangs/crashes on launch

    Hi there, Hope you guys can help me out a bit here. Every single time I launch mail.app, it hangs. It doesn't crash, it just hangs. In the Force Quit applications window, all I see is "Mail (not responding)". I can force it to quit, at which point th

  • Update Serial Numbers to Production Order

    Hi, Has anyone used any Function module for updating the Serial Numbers to the Production Order Header. I am using the FM - SERNR_ADD_TO_PP . The Serial Numbers needs to be assigned when doing Goods Issue in MIGO. At this point The FM is updating the

  • Error in the tutorial OnlineInteractiveForm

    Hi, i´m doing this tutorial that use Adobe Service, i download de program complete for see the application, but when i execute, appear this error:     com.sap.tc.webdynpro.pdfobject.core.PDFObjectRuntimeException: Processing exception during a "Usage