CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2009
    Posts
    32

    Two Identically Constructed Objects Aren't Equal , And I Don't Know Why

    Code:
    public class Test {
      public static void main(String[] args) {
        StringByComposition a = new StringByComposition("announce");
        StringByComposition b = new StringByComposition("announce");
        System.out.println(a.equals(b));
      }
    }
    class StringByComposition {
      public String composedString;
      public StringByComposition(String s) {
        composedString = s;
      }
    }
    This code outputs false every time I run I. I constructed the class with identical strings. I thought that two objects of the same class that have all identical fields will be equal to each according to the equals method.

    What is going wrong? Please help, although I kinda already knew the answer to my previous question, I have no idea what to do with this one.

    --Hold on, when I override the equals method, I get true...
    Code:
    public class Test {
      public static void main(String[] args) {
        StringByComposition a = new StringByComposition("announce");
        StringByComposition b = new StringByComposition("announce");
        System.out.println(a.equals(b));
      }
    }
    class StringByComposition {
      public String composedString;
      public StringByComposition(String s) {
        composedString = s;
      }
      public boolean equals(Object o) {
        if (o instanceof StringByComposition) {
          return composedString.equals(((StringByComposition)o).composedString);
        }
        return false;
      }
    }
    Can some one explain to me why I need to override the equals method?

  2. #2
    Join Date
    Feb 2008
    Posts
    966

    Re: Two Identically Constructed Objects Aren't Equal , And I Don't Know Why

    Because the default implementation of the equals method compares the memory addresses for each object. If you want to compare something else, such as fields, you need to override equals from Object and tell it exactly what it means to be equal for your object.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured