Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming

Chapter 23

1. 

Why do you think it is important for objects to behave well?

2. 

What are the seven object usage scenarios you should be aware of when designing a class?

3. 

What five methods of the java.lang.Object class are most often overridden?

4. 

What is the purpose of the toString() method?

5. 

What is the purpose of the equals() method?

6. 

What are the five elements of the equals() method equivalence relation as stated in the Java Platform API documentation?

7. 

What is the purpose of the hashCode() method?

8. 

What is the general contract of the hashCode() method as stated in the Java Platform API documentation?

9. 

How does a class’s hashCode() method behavior depend upon the behavior provided by the class’s equals() method?

10. 

What type of ordering does the Compareable.compareTo() method impose upon a class of objects?

Answers

1. 

- so their use within a program is predictable

2. 

- string representation; comparison against other object in class for equality; usage in hashtable-based collections; cloning; natural ordering; total ordering; sent via a network or saved to disk

3. 

- toString(), clone(), hashCode(), equals(), finalize()

4. 

- provides a string representation of the object

5. 

- used to logically compare object of the same class

6. 

- reflexive, symmetric, transitive, consistent, non-null reference x.equals(null) should return false

7. 

- provides a unique integer value for unique objects of a particular class

8. 

The hashCode() method must consistently return the same integer when invoked on the same object more than once during an execution of a Java application provided no information used in equals() comparisons on the object is modified. This integer need not remain constant from one execution of an application to another execution of the same application.

The hashCode() method must produce the same results when called on two objects if they are equal according to the equals() method.

The hashCode() method is not required to return distinct integer results for logically unequal objects, however, failure to do so may result in degraded hashtable performance.

9. 

- the hashCode() must behave consistently with the equals() method

10. 

- Natural ordering

Категории