An Integer List

Example 2-7 is a class that implements a list or growable array of int values. This IntList class is like the java.util.ArrayList class, but it works with primitive int values rather than objects. When you need to store int values and do not know the number of values in advance (i.e., you can’t use an array), IntList is much more efficient than using an ArrayList because there is no need to wrap your int values in Integer objects. The interesting thing about this example is not its efficiency, however, but the fact that it is a real-world example: the code is nontrivial but easy to understand, and the class actually serves a useful purpose.

Also interesting is the fact that this class overrides a number of methods inherited from Object in order to provide meaningful implementations. Like the ComplexNumber class of Example 2-5, this class defines a toString( ) method to convert its state to a textual representation that can be displayed in log messages, debugging statements, and elsewhere. Additionally, it overrides the equals( ) method to determine if two IntList objects are equal. It also overrides the hashCode( ) method to provide a compatible implementation that ensures that IntList objects that are equal have the same hash code. This enables IntList objects to be used as keys in hashtables such as the java.util.HashMap class.

The Object class also defines the clone( ) or finalize( ) methods, but neither method is recommend for general use, and IntList does ...

Get Java Examples in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.