• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is the "general contracts"?  RSS feed

 
Ilkin Abdullayev
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I started reading Effective Java(Joshua Bloch) and I'm currently at Chapter 3.


ALTHOUGH Object is a concrete class, it is designed primarily for extension. All
of its nonfinal methods (equals, hashCode, toString, clone, and finalize) have
explicit general contracts because they are designed to be overridden.


I don't understand which this is particularly mentioned the "general contracts".

I would be glad if you can help
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

It means that all of the non-final methods of class Object (the methods: equals, hashCode, toString, clone and finalize) are supposed to work in a certain way, that is described in the documentation.

With the word "contract" is meant that there are certain rules that you must follow when you override these methods. For example, equals() and hashCode() have to be implemented in a certain way, otherwise you will get strange results when you put objects of your class in a hash-based collection such as a HashSet.

The API documentation of class java.lang.Object describes those rules for each of the methods.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again

You have chosen a difficult example. Although the general contract for equals() is very easy to understand, it is notoriously difficult to implement. If you read the remainder of the chapter in Bloch you will see some of the problems.
Jesper de Jong wrote:For example, equals() and hashCode() have to be implemented in a certain way, otherwise you will get strange results when you put objects of your class in a hash-based collection such as a HashSet.
That means, if you don't fulfil the general contract for equals() and hashCode(), the methods of HashMap/HashSet will not behave according to their general contract. Even though HashSet is implemented correctly you might be able to do this sort of thing:-
 
Ilkin Abdullayev
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!