The Collection Interface
The Collection interface is’ the foundation upon which the collections framework is built. It declares the core methods that all collections will have. Because all collections implement Collection, familiarity with its methods is necessary for a dear understanding of the framework. Several of these methods can throw an Unsupported Operation Exception. As explained, this occurs if a collection cannot be modified. A Class Cast Exccption is generated when one object is incompatible with another, such as when an attempt is made to add an incompatible object to a collection. Objects are added to a collection by calling add(). Notice that adJ( ),takes an argument of type Object. Because Object is a superclass of all classes, ,.ny type of object may be stored in a collection. However, primitive types mdY I.Ot. For example, a collection cannot directly store values of type int, char, double, and Oth. Of course. if o u want to store such objects, You can add the entire contents of one cl action to another b calling addAll( ).
You can remove an object by using removc( ). To remove a gUlp of objects, call remove All(). You can remove all clements except those of a special group by calling rctain All( ).’To empty a collection, call clear .You can determine whether a collection contains a specific object by calling contains(). To determine whether one collection contains all Ii.e I .embers of another, call containsAll(). You can determine when a collection is empty ling isEmpty(). The number of elements currently held in a collection can be delet line. I by calling size( ).
The toArray() method returns an array that contains the elr- ucnt ‘ stored in the invoking collection. TIU smethod is more important than it migl ‘l at Lrst seem. Often, processing the contents of a collection by using array-like syntax is advantageous. By , providing a pathway between collections and arrays, you can the best of both worlds. Two collections can be compared for equality by calling cqualst). The precise . meaning of “equality” may differ from collection to collection. For example, you can implement equals() so that it compares the values of elements stored in the collection. , Alternatively, equalst ) can compare references to those elements. . One more very important method is iterator( ), which returns an iter ator to a collection. As you will see, iterators arc crucial to successful programming when using the collections framework.