Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: equals() method.

  1. #1
    Member
    Join Date
    Sep 2011
    Posts
    83
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default equals() method.

    Hi, in my code I have

    public boolean equals(Object obj) {
    		if (this.equals(obj)){
    			return true;
    		}
    		return false;
    	}

    Im just making sure I know what the equals method does...

    Does this check if all of the attributes in 'obj' are this same as in the object the method belongs to?

    Thanks.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: equals() method.

    You can define equals to behave however you wish to define object equality. The way you have written, you will create an infinite loop. Often, equals should check for a null parameter and return false if it is null. Then go to check things you wish to check - for instance of the object is an instanceof the class you are checking, then compare the equality of the variables of the objects (whichever variables you wish to use to define equality).

    You should also read the API for info on how to correctly override this method
    Object (Java Platform SE 6)

  3. #3
    Member
    Join Date
    Sep 2011
    Posts
    83
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: equals() method.

    Thanks.

Similar Threads

  1. [SOLVED] Noobie equals() problem.
    By ViRAL in forum What's Wrong With My Code?
    Replies: 6
    Last Post: November 12th, 2011, 03:29 AM
  2. Using the .equals method
    By TenaciousE in forum Java Theory & Questions
    Replies: 2
    Last Post: October 23rd, 2011, 05:24 PM
  3. Method Equals, Boolean...
    By boys8goods in forum Object Oriented Programming
    Replies: 1
    Last Post: June 25th, 2011, 03:34 PM
  4. [SOLVED] Difference between == and equals.
    By goldest in forum What's Wrong With My Code?
    Replies: 9
    Last Post: December 18th, 2010, 03:15 PM
  5. Equals Method
    By Sninald in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 18th, 2010, 03:06 AM