Vous êtes sur la page 1sur 23

Collection API

Q1.) What is the Collections API?


A 1.) The Collections API is a set of classes and interfaces that support operations on
collections of objects.

Q 2.) What is the List interface?


A 2.) The List interface provides support for ordered collections of objects.

Q 3.) What is the Vector class?


A 3.) The Vector class provides the capability to implement a growable array of
objects.

Q 4.) What is an Iterator interface?


A 4.) The Iterator interface is used to step through the elements of a Collection.

Q 5.) Which java.util classes and interfaces support event handling?


A 5.) The EventObject class and the EventListener interface support event
processing.

Q 6.) What is the GregorianCalendar class?


A 6.) The GregorianCalendar provides support for traditional Western calendars

Q 7.) What is the Locale class?


A 7.) The Locale class is used to tailor program output to the conventions of a
particular geographic, political, or cultural region.

Q 8.) What is the SimpleTimeZone class?


A 8.) The SimpleTimeZone class provides support for a Gregorian calendar.

Q 9.) What is the Map interface?


A 9.) The Map interface replaces the JDK 1.1 Dictionary class and is used associate
keys with values.

Q 10.) What is the highest-level event class of the event-delegation model?


A 10.) The java.util. EventObject class is the highest-level class in the event-
delegation class hierarchy.

Q 11.) What is the Collection interface?


A 11.) The Collection interface provides support for the implementation of a
mathematical bag - an unordered collection of objects that may contain duplicates.

Q 12.) What is the Set interface?


A 12.) The Set interface provides methods for accessing the elements of a finite
mathematical set. Sets do not allow duplicate elements.
Q 13.) What is the typical use of Hash table?
A 13.) Whenever a program wants to store a key value pair, one can use Hash table.

Q 14.) I am trying to store an object using a key in a Hashtable. And some


other object already exists in that location, then what will happen? The
existing object will be overwritten? Or the new object will be stored
elsewhere?
A 14.) The existing object will be overwritten and thus it will be lost.

Q 15.) What is the difference between the size and capacity of a Vector?
A 15.) The size is the number of elements actually stored in the vector, while capacity
is the maximum number of elements it can store at a given instance of time.

Q 16.) Can a vector contain heterogeneous objects?


A 16.) Yes a Vector can contain heterogeneous objects. Because a Vector stores
everything in terms of Object.

Q 17.) Can an ArrayList contain heterogeneous objects?


A 17.) Yes a ArrayList can contain heterogeneous objects. Because a ArrayList stores
everything in terms of Object.

Q 18.) What is an enumeration?


A 18.) An enumeration is an interface containing methods for accessing the
underlying data structure from which the enumeration is obtained. It is a construct
which collection classes return when you request a collection of all the objects stored
in the collection. It allows sequential access to all the elements stored in the
collection.

Q 19.) Considering the basic properties of Vector and ArrayList, where will
you use Vector and where will you use ArrayList?
A 19.) The basic difference between a Vector and an ArrayList is that, vector is
synchronized while ArrayList is not. Thus whenever there is a possibility of multiple
threads accessing the same instance, one should use Vector. While if not multiple
threads are going to access the same instance then use ArrayList. Non-synchronized
data structure will give better performance than the synchronized one.

Q 20.) Can a vector contain heterogeneous objects?


A 20.) Yes a Vector can contain heterogeneous objects. Because a Vector stores
everything in terms of Object.
Get started with the Java
Collections Framework
Find out how Sun's new offering can help you to make
your collections more useful and accessible
Summary
Just when you thought you had Java well in hand, Sun goes and adds
more goodies to the package. The Java Collections Framework,
standard in JDK 1.2 and available for Java 1.1, offers developers a
common way to implement and access collections. Java developer Dan
Becker examines this new framework, detailing the basic concrete
implementations and the general-purpose methods for sorting and
manipulating collections. (2,900 words)

By Dan Becker

DK 1.2 introduces a new framework for collections of objects, called the Java
Collections Framework. "Oh no," you groan, "not another API, not another framework
to learn!" But wait, before you turn away, hear me out: the Collections framework is
worth your effort and will benefit your programming in many ways. Three big
benefits come immediately to mind:

• It dramatically increases the readability of your collections by providing a


standard set of interfaces to be used by many programmers in many
applications.
• It makes your code more flexible by allowing you to pass and return
interfaces instead of concrete classes, generalizing your code rather than
locking it down.
• It offers many specific implementations of the interfaces, allowing you to
choose the collection that is most fitting and offers the highest performance
for your needs.

And that's just for starters.


Our tour of the framework will begin with an overview of the advantages it provides
for storing sets of objects. As you'll soon discover, because your old workhorse
friends Hashtable and Vector support the new API, your programs will be uniform
and concise -- something you and the developers accessing your code will certainly
cheer about.
After our preliminary discussion, we'll dig deeper into the details.
The Java Collections advantage: An overview
Before Collections made its most welcome debut, the standard methods for grouping
Java objects were via the array, the Vector, and the Hashtable. All three of these
collections have different methods and syntax for accessing members: arrays use the
square bracket ([]) symbols, Vector uses the elementAt method, and Hashtable
uses get and put methods. These differences have long led programmers down the
path to inconsistency in implementing their own collections -- some emulate the
Vector access methods and some emulate the Enumeration interface.
To further complicate matters, most of the Vector methods are marked as final; that
is, you cannot extend the Vector class to implement a similar sort of collection. We
could create a collection class that looked like a Vector and acted like a Vector, but
it couldn't be passed to a method that takes a Vector as a parameter.
Finally, none of the collections (array, Vector or Hashtable) implements a standard
member access interface. As programmers developed algorithms (like sorts) to
manipulate collections, a heated discourse erupted on what object to pass to the
algorithm. Should you pass an array or a Vector? Should you implement both
interfaces? Talk about duplication and confusion.
Thankfully, the Java Collections Framework remedies these problems and offers a
number of advantages over using no framework or using the Vector and Hashtable:

• A usable set of collection interfaces

By implementing one of the basic interfaces -- Collection, Set, List, or Map


-- you ensure your class conforms to a common API and becomes more
regular and easily understood. So, whether you are implementing an SQL
database, a color swatch matcher, or a remote chat application, if you
implement the Collection interface, the operations on your collection of
objects are well-known to your users. The standard interfaces also simplify
the passing and returning of collections to and from class methods and allow
the methods to work on a wider variety of collections.

• A basic set of collection implementations

In addition to the trusty Hashtable and Vector, which have been updated to
implement the Collection interfaces, new collection implementations have
been added, including HashSet and TreeSet, ArrayList and LinkedList, and
HashMap and Map. Using an existing, common implementation makes your
code shorter and quicker to download. Also, using existing Core Java code
core ensures that any improvements to the base code will also improve the
performance of your code.

• Other useful enhancements

Each collection now returns an Iterator, an improved type of Enumeration


that allows element operations such as insertion and deletion. The Iterator is
"fail-fast," which means you get an exception if the list you're iterating is
changed by another user. Also, list-based collections such as Vector return a
ListIterator that allow bi-directional iteration and updating.

Several collections (TreeSet and TreeMap) implicitly support ordering. Use


these classes to maintain a sorted list with no effort. You can find the smallest
and largest elements or perform a binary search to improve the performance
of large lists. You can sort other collections by providing a collection-compare
method (a Comparator object) or an object-compare method (the
Comparable interface).

Finally, a static class Collections provides unmodifiable (read-only) and


synchronized versions of existing collections. The unmodifiable classes are
helpful to prevent unwanted changes to a collection. The synchronized version
of a collection is a necessity for multithreaded programs.

The Java Collections Framework is part of Core Java and is contained in the
java.util.collections package of JDK 1.2. The framework is also available as a
package for JDK 1.1

Note: The JDK 1.1 version of collections is named com.sun.java.util.collections.


Keep in mind that code developed with the 1.1 version must be updated and
recompiled for the 1.2 version, and any objects serialized in 1.1 cannot be
deserialized into 1.2.
Let us now look more closely at these advantages by exercising the Java Collections
Framework with some code of our own.

A good API

The first advantage of the Java Collections Framework is a consistent and regular
API. The API is codified in a basic set of interfaces, Collection, Set, List, or
Map. The Collection interface contains basic collection operations such as adding,
removing, and tests for membership (containment). Any implementation of a
collection, whether it is one provided by the Java Collections Framework or one of
your own creations, will support one of these interfaces. Because the Collections
framework is regular and consistent, you will learn a large portion of the frameworks
simply by learning these interfaces.

Both Set and List implement the Collection interface. The Set interface is
identical to the Collection interface except for an additional method, toArray,
which converts a Set to an Object array. The List interface also implements the
Collection interface, but provides many accessors that use an integer index into the
list. For instance, get, remove, and set all take an integer that affects the indexed
element in the list. The Map interface is not derived from collection, but
provides an interface similar to the methods in java.util.Hashtable. Keys are used
to put and get values. Each of these interfaces is described in following code
examples.
The following code segment demonstrates how to perform many Collection
operations on HashSet, a basic collection that implements the Set interface. A
HashSet is simply a set that doesn't allow duplicate elements and doesn't
order or position its elements. The code shows how you create a basic collection
and add, remove, and test for elements. Because Vector now supports the
Collection interface, you can also execute this code on a vector, which you can test
by changing the HashSet declaration and constructor to a Vector.

import java.util.collections.*;
public class CollectionTest {
// Statics
public static void main( String [] args ) {
System.out.println( "Collection Test" );

// Create a collection
HashSet collection = new HashSet();
// Adding
String dog1 = "Max", dog2 = "Bailey", dog3 = "Harriet";
collection.add( dog1 );
collection.add( dog2 );
collection.add( dog3 );

// Sizing
System.out.println( "Collection created" +
", size=" + collection.size() +
", isEmpty=" + collection.isEmpty() );

// Containment
System.out.println( "Collection contains " + dog3 +
": " + collection.contains( dog3 ) );

// Iteration. Iterator supports hasNext, next, remove


System.out.println("Collection iteration (unsorted):" );
Iterator iterator = collection.iterator();
while ( iterator.hasNext() )
System.out.println( " " + iterator.next() );

// Removing
collection.remove( dog1 );
collection.clear();
}
}
Let's now build on our basic knowledge of collections and look at other interfaces and
implementations in the Java Collections Framework.
Good concrete implementations
We have exercised the Collection interface on a concrete collection, the HashSet.
Let's now look at the complete set of concrete collection implementations provided in
the Java Collections framework.

Implementations
Hash Resizable Balanced Tree Linked
Legacy
Table Array (Sorted) List
Set HashSet * TreeSet * *

Interfaces List * ArrayList * LinkedList Vector


Map HashMap * TreeMap * Hashtable

Implementations marked with an asterix (*) make no sense or provide no compelling


reason to implement. For instance, providing a List interface to a Hash Table makes
no sense because there is no notion of order in a Hash Table. Similarly, there is no
Map interface for a Linked List because a list has no notion of table lookup.

Let's now exercise the List interface by operating on concrete implementations that
implement the List interface, the ArrayList, and the LinkedList. The code below is
similar to the previous example, but it performs many List operations.
import java.util.collections.*;
public class ListTest {
// Statics
public static void main( String [] args ) {
System.out.println( "List Test" );

// Create a collection
ArrayList list = new ArrayList();

// Adding
String [] toys = { "Shoe", "Ball", "Frisbee" };
list.addAll( Arrays.toList( toys ) );

// Sizing
System.out.println( "List created" +
", size=" + list.size() +
", isEmpty=" + list.isEmpty() );

// Iteration using indexes.


System.out.println( "List iteration (unsorted):" );
for ( int i = 0; i < list.size(); i++ )
System.out.println( " " + list.get( i ) );

// Reverse Iteration using ListIterator


System.out.println( "List iteration (reverse):" );
ListIterator iterator = list.listIterator( list.size() );
while ( iterator.hasPrevious() )
System.out.println( " " + iterator.previous() );

// Removing
list.remove( 0 );
list.clear();
}
}
As with the first example, it's simple to swap out one implementation for
another. You can use a LinkedList instead of an ArrayList simply by
changing the line with the ArrayList constructor. Similarly, you can use a
Vector, which now supports the List interface.
When deciding between these two implementations, you should consider whether the
list is volatile (grows and shrinks often) and whether access is random or ordered.
My own tests have shown that the ArrayList generally outperforms the
LinkedList and the new Vector.
Notice how we add elements to the list: we use the addAll method and the static
method Arrays.toList. This static method is one of the most useful utility
methods in the Collections framework because it allows any array to be
viewed as a List. Now an array may be used anywhere a Collection is needed.

Notice that I iterate through the list via an indexed accessor, get, and the
ListIterator class. In addition to reverse iteration, the ListIterator class
allows you to add, remove, and set any element in the list at the point
addressed by the ListIterator. This approach is quite useful for filtering or
updating a list on an element-by-element basis.
The last basic interface in the Java Collections Framework is the Map. This interface
is implemented with two new concrete implementations, the TreeMap and the
HashMap. The TreeMap is a balanced tree implementation that sorts
elements by the key.
Let's illustrate the use of the Map interface with a simple example that shows how to
add, query, and clear a collection. This example, which uses the HashMap class, is
not much different from how we used the Hashtable prior to the debut of the
Collections framework. Now, with the update of Hashtable to support the Map
interface, you can swap out the line that instantiates the HashMap and replace it
with an instantiation of the Hashtable.

import com.sun.java.util.collections.*;
public class HashMapTest {
// Statics
public static void main( String [] args ) {
System.out.println( "Collection HashMap Test" );

HashMap collection1 = new HashMap();

// Test the Collection interface


System.out.println( "Collection 1 created, size=" + collection1.size() +
", isEmpty=" + collection1.isEmpty() );

// Adding
collection1.put( new String( "Harriet" ), new String( "Bone" ) );
collection1.put( new String( "Bailey" ), new String( "Big Chair" ) );
collection1.put( new String( "Max" ), new String( "Tennis Ball" ) );

System.out.println( "Collection 1 populated, size=" + collection1.size() +


", isEmpty=" + collection1.isEmpty() );

// Test Containment/Access
String key = new String( "Harriet" );
if ( collection1.containsKey( key ) )
System.out.println( "Collection 1 access, key=" + key + ", value=" +
(String) collection1.get( key ) );

// Test iteration of keys and values


Set keys = collection1.keySet();
System.out.println( "Collection 1 iteration (unsorted), collection contains
keys:" );
Iterator iterator = keys.iterator();
while ( iterator.hasNext() )
System.out.println( " " + iterator.next() );

collection1.clear();
System.out.println( "Collection 1 cleared, size=" + collection1.size() +
", isEmpty=" + collection1.isEmpty() );
}
}
We've covered most of the interfaces and implementations in the Java Collections
framework, and we're ready to check out some of the additional capabilities
Collections offers us.
Other capabilities
Many of the additional features such as sorting and synchronization are encapsulated
in the Collections and Arrays classes. These classes, which will appear throughout
the following discussion, provide static methods for acting on collections.
Sorting a collection
We'll begin by exploring sorting. Two of the concrete implementations in the Java
Collections Framework provide easy means to maintain a sorted collection: TreeSet
and TreeMap. In fact, these two classes implement the SortedSet and SortedMap
interfaces, which are similar to their unsorted counterparts except that they provide
methods to access first and last elements and portions of the sorted collections.
There are two basic techniques for maintaining a sorted collection. The first uses one
of the sorted collection classes and provides the collection with an object that
implements a comparison via the Comparator interface. For example, going back to
our first code example, we can sort our collection by creating a StringComparator
and adding it to the end of the code, as shown here:

// This class sorts two String objects.


class StringComparator implements Comparator {
public int compare( Object object1, Object object2 ) {
return ((String) object1).compareTo( (String) object2 );
}
}
Next, we need to change the collection from a HashSet (unsorted) to a HashMap
(sorted with our StringComparator by using the following constructor:

TreeSet collection = new TreeSet( new StringComparator() );

Rerun the example and you should see that the iteration is performed in sorted
order. Because the collection is ordered, you should now be able to find the min and
the max elements using the static class Collections.
The second technique is to implement natural ordering of a class by making the class
implement the Comparable interface. This technique adds a single compareTo
method to a class, which then returns 0 for equal objects, less than 0 if the first
parameter is less than the second, or greater than 0 of the first parameter is greater
than the second. In Java 1.2, the String class (but not StringBuffer) implements
the Comparable interface. Any comparable object can be placed in a sorted
collection, and the collection order is maintained automatically by the collection.
You can also sort Lists by handing them to the Collections class. One static sort
method takes a single List parameter that specifies a naturally ordered class (one
that implements the Comparable interface). A second static sort method takes a
Comparator object for other classes that do not implement the Comparable
interface.
Unmodifiable collections
The Collections class provides many static factory methods (like
Collection.unmodifiableCollection and Collection.unmodifiableSet) for providing
unmodifiable or immutable collections. In fact, there is one method for each of the
basic collection interfaces. These methods are extremely useful to ensure that no one
modifies your collection. For instance, if you want to allow others to see your list but
not change it, you may implement a method that returns an unmodifiable view of
your collection. Here's an example:

List getUnmodifieableView() {
return Collections.unmodifableList( this );
}
This code will throw an UnsupportedOperationException, one of the
RuntimeExceptions, if someone trys to add or remove an element from the list.
Unfortunately, the unmodifiable views of a collection are of the same type as the
original collection, which hinders compile-time type checking. Although you may pass
an unmodifiable list to a method, by virtue of its type, the compiler has no way of
ensuring the collection is unchanged by the method. The unmodifiable collection is
checked at runtime for changes, but this is not quite as strong as compile-time
checking and does not aid the compiler in code optimization. Perhaps it's time for
Java to emulate C++'s const and add another modifier signifying immutability of any
method, class, or object.
Synchronized collections
Finally, note that none of the concrete methods mentioned thus far support
multithreaded access in the manner that the Vectors and Hashtable did. In other
words, none of the methods on the concrete implementations are synchronized and
none of the implementations are thread-safe. You must support thread safety
yourself.
This may seem like a major omission, but in actuality it's not really a big problem.
The Collections class provides a synchronized version of each of the collection
implementations. You ensure thread safety by using the synchronized version of a
collection and synchronizing on the returned object. For example, we can ensure
thread safety on a List by using the following construct:

List dogs = synchronized List( new ArrayList() );


synchronized( list ) {
Iterator iterator = list.iterator(); // Must be in synchronized block
while ( iterator.hasNext() )
nonAtomicOperation( iterator.next() );
}
Many programmers are already using these types of synchronized blocks around
Vectors and Hashtables, so the new considerations aren't too significant.
Conclusion
That concludes our survey of the new Java Collections Framework. We covered a lot
of territory, so let's briefly review. We began with a look at the interfaces, which are
used through the API and are useful for any new collections we may create. These
interfaces are intuitive and provide a common way for all Java programmers to
access collections. By implementing a common interface in the Collections
framework, you make it easy for other programmers to access your collection, you
reduce the time it takes for others to learn your class, and you make your class more
useful.
We also examined the basic concrete implementations provided with the framework.
You can use these basic collections to implement any generic collection of Java
objects. Like the existing Vector and Hashtable, these new collection
implementations will cover a majority of your needs as a developer.
Finally, we looked at several general-purpose methods for sorting and manipulating
collections. The sort interfaces are easy to add to any class, and the Collections sort
methods will knock a few deliverables out of your code package.

Some Good CODE Snippets::

-- Check for empty collection

Collection c= new Collection();


//new collection, so it is empty
if (c.isEmpty()){
System.out.println("Collection is empty"); //this prints
}else{
System.out.println("Collection is NOT empty"); //this does not print
}

-- //Collection is abstract. so it can not be instantiated. to create an empty collection


assign null to it.
// Instantiating like --> Collection = new Collection(); ...will throw an error
Collection c = null;
//new collection, so it is empty
if (c.isEmpty()){
System.out.println("Collection is empty"); //this prints
}else{
System.out.println("Collection is NOT empty"); //this does not print
}

-- Collection list= new ArrayList();


if(list.isEmpty())
System.out.println(" Collection is empty ");
else
System.out.println(" Collection is not empty ");

Java Collection Framework

We have tried you to make a walk through the Collection Framework. The Collection
Framework provides a well-designed set if interface and classes for sorting and
manipulating groups of data as a single unit, a collection.

The Collection Framework provides a standard programming interface to many of the


most common abstractions, without burdening the programmer with too many
procedures and interfaces.

The Collection Framework is made up of a set of interfaces for working with the
groups of objects. The different interfaces describe the different types of groups. For
the most part, once you understand the interfaces, you understand the framework.
While you always need to create specific, implementations of the interfaces, access
to the actual collection should be restricted to the use of the interface methods, thus
allowing you to change the underlying data structure, without altering the rest of
your code.

In the Collections Framework, the interfaces Map and Collection are distinct with no
lineage in the hierarchy. The typical application of map is to provide access to values
stored by keys.

When designing software with the Collection Framework, it is useful to remember the
following hierarchical relationship of the four basic interfaces of the framework.

• The Collection interface is a group of objects, with duplicates allowed.


• Set extends Collection but forbids duplicates.
• List extends Collection also, allows duplicates and introduces positional
indexing.
• Map extends neither Set nor Collection

Interface Implementation Historical

Set HashSet TreeSet

Vector
List ArrayList LinkedList
Stack
Hashtable
Map HashMap TreeMap
Properties

The historical collection classes are called such because they have been around since
1.0 release of the java class libraries. If you are moving from historical collection to
the new framework classes, one of the primary differences is that all operations are
synchronized with the new classes. While you can add synchronization to the new
classes, you cannot remove from the old.

Java Collection Framework - Collection Interface


The Collection interface is used to represent any group of objects, or elements. Here is a
list of the public methods of the Collection Interface.
boolea add (Object o)
n Ensures that this collection contains the specified element (optional operation).
boolean addAll(Collection c)
Adds all of the elements in the specified collection to this collection (optional
operation).
void clear()
Removes all of the elements from this collection (optional operation).
boolean contains(Object o)
Returns true if this collection contains the specified element.
boolean containsAll(Collection c)
Returns true if this collection contains all of the elements in the specified
collection.
boolean equals(Object o)
Compares the specified object with this collection for equality.
int hashCode()
Returns the hash code value for this collection.
boolean isEmpty()
Returns true if this collection contains no elements.
Iterator iterator()
Returns an iterator over the elements in this collection.
boolean remove(Object o)
Removes a single instance of the specified element from this collection, if it is
present (optional operation).
boolean removeAll(Collection c)
Removes all this collection's elements that are also contained in the specified
collection (optional operation).
boolean retainAll(Collection c)
Retains only the elements in this collection that are contained in the specified
collection (optional operation).
int size()
Returns the number of elements in this collection.
Object toArray()
[] Returns an array containing all of the elements in this collection.
Object toArray(Object[] a)
[] Returns an array containing all of the elements in this collection; the runtime
type of the returned array is that of the specified array.
The interface supports basic operations like adding and removing. When you try to
remove an element, only a single instance of the element in the collection is removed, if
present.

boolean add (Object o)


boolean remove(Object o)
The Collection interface also supports query operations
int size()
boolean isEmpty()
boolean contains(Object o)
Iterator iterator()

Java Collection Framework - Iterator Interface

The iterator() method of the Collection interface returns and Iterator. An Iterator is
similar to the Enumeration interface, Iterators differ from enumerations in two ways:

1.Iterators allow the caller to remove elements from the underlying collection during
the iteration with well-defined semantics.
2. Method names have been improved.

boolea hasNext()
n Returns true if the iteration has more elements.
Object next()
Returns the next element in the iteration.

void remove()
Removes from the underlying collection the last element returned by the
iterator (optional operation).

The remove method is optionally supported by the underlying collection. When called
and supported, the element returned by the last next() call is removed.

Java Collection Framework - Set Interface

The set interface extends the Collection interface and, by definition, forbids
duplicates within the collection. All the original methods are present and no new
method is introduced. The concrete Set implementation classes rely on the equals ()
method of the object added to check for equality.

void add(int index, Object element)


Inserts the specified element at the specified position in this list (optional
operation).
boolean add(Object o)
Appends the specified element to the end of this list (optional operation).

boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this
list, in the order that they are returned by the specified collection's
Iterator (optional operation).
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list at the
specified position (optional operation).

void clear()
Removes all of the elements from this list (optional operation).

boolean contains(Object o)
Returns true if this list contains the specified element.

boolean containsAll(Collection c)
Returns true if this list contains all of the elements of the specified
collection.

boolean equals(Object o)
Compares the specified object with this list for equality.

Object get(int index)


Returns the element at the specified position in this list.

int hashCode()
Returns the hash code value for this list.

int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified
element, or -1 if this list does not contain this element.

boolean isEmpty()
Returns true if this list contains no elements.

Iterator iterator()
Returns an iterator over the elements in this list in proper sequence.
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified
element, or -1 if this list does not contain this element.

ListIterator listIterator()
Returns a list iterator of the elements in this list (in proper sequence).

ListIterator listIterator(int index)


Returns a list iterator of the elements in this list (in proper sequence),
starting at the specified position in this list.

Object remove(int index)


Removes the element at the specified position in this list (optional
operation).

boolean remove(Object o)
Removes the first occurrence in this list of the specified element (optional
operation).

boolean removeAll(Collection c)
Removes from this list all the elements that are contained in the specified
collection (optional operation).

boolean retainAll(Collection c)
Retains only the elements in this list that are contained in the specified
collection (optional operation).

Object set(int index, Object element)


Replaces the element at the specified position in this list with the
specified element (optional operation).

int size()
Returns the number of elements in this list.

List subList(int fromIndex, int toIndex)


Returns a view of the portion of this list between the specified fromIndex,
inclusive, and toIndex, exclusive.

Object[] toArray()
Returns an array containing all of the elements in this list in proper
sequence.

Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in proper
sequence; the runtime type of the returned array is that of the specified
array.

About the HASHCODE:

public int hashCode()

Returns a hash code value for the object. This method is supported for the
benefit of hashtables such as those provided by java.util.Hashtable.
The general contract of hashCode is:
Whenever it is invoked on the same object more than once during an execution
of a Java application, the hashCode method must consistently return the same
integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the
hashCode method on each of the two objects must produce the same integer
result.
It is not required that if two objects are unequal according to the
equals(java.lang.Object) method, then calling the hashCode method on each of
the two objects must produce distinct integer results. However, the programmer
should be aware that producing distinct integer results for unequal objects may
improve the performance of hashtables.
As much as is reasonably practical, the hashCode method defined by class
Object does return distinct integers for distinct objects. (This is typically
implemented by converting the internal address of the object into an integer, but
the Java TM programming language does not require this implementation
technique.)

Returns:
a hash code value for this object.

Java Collection Framework - List Interface

This is an ordered collection (also known as a sequence). The List interface


extends the Collection interface to define an ordered collection, permitting
duplicates. The user of this interface has precise control over where in the list
each element is inserted. The user can access elements by their integer index
(position in the list), and search for elements in the list.

boolean add (Object o)


Ensures that this collection contains the specified element (optional
operation).
boolean addAll(Collection c)
Adds all of the elements in the specified collection to this collection
(optional operation).
void clear()
Removes all of the elements from this collection (optional operation).
boolean contains(Object o)
Returns true if this collection contains the specified element.
boolean containsAll(Collection c)
Returns true if this collection contains all of the elements in the specified
collection.
boolean equals(Object o)
Compares the specified object with this collection for equality.
int hashCode()
Returns the hash code value for this collection.
boolean isEmpty()
Returns true if this collection contains no elements.
Iterator iterator()
Returns an Iterator over the elements in this collection.
boolean remove(Object o)
Removes a single instance of the specified element from this collection,
if it is present (optional operation).
boolean removeAll(Collection c)
Removes all this collection's elements that are also contained in the
specified collection (optional operation).
boolean retainAll(Collection c)
Retains only the elements in this collection that are contained in the
specified collection (optional operation).
int size()
Returns the number of elements in this collection.
Object[] toArray()
Returns an array containing all of the elements in this collection.
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this collection; the
runtime type of the returned array is that of the specified array.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically
allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically
allow multiple null elements if they allow null elements at all. It is not
inconceivable that someone might wish to implement a list that prohibits
duplicates, by throwing runtime exceptions when the user attempts to insert
them, but we expect this usage to be rare.
The List interface places additional stipulations, beyond those specified in the
Collection interface, on the contracts of the iterator, add, remove, equals, and
hashCode methods. Declarations for other inherited methods are also included
here for convenience.
The List interface provides four methods for positional (indexed) access to list
elements. Lists (like Java arrays) are zero based. Note that these operations may
execute in time proportional to the index value for some implementations (the
LinkedList class, for example). Thus, iterating over the elements in a list is
typically preferable to indexing through it if the caller does not know the
implementation.
The List interface provides a special iterator, called a ListIterator, that allows
element insertion and replacement, and bi-directional access in addition to the
normal operations that the Iterator interface provides. A method is provided to
obtain a list iterator that starts at a specified position in the list.
The List interface provides two methods to search for a specified object. From a
performance standpoint, these methods should be used with caution. In many
implementations they will perform costly linear searches.
The List interface provides two methods to efficiently insert and remove multiple
elements at an arbitrary point in the list.
Note: While it is permissible for lists to contain themselves as elements, extreme
caution is advised: the equals and hashCode methods are no longer well defined
on a such a list.
Some list implementations have restrictions on the elements that they may
contain. For example, some implementations prohibit null elements, and some
have restrictions on the types of their elements. Attempting to add an ineligible
element throws an unchecked exception, typically NullPointerException or
ClassCastException. Attempting to query the presence of an ineligible element
may throw an exception, or it may simply return false; some implementations will
exhibit the former behavior and some will exhibit the latter. More generally,
attempting an operation on an ineligible element whose completion would not
result in the insertion of an ineligible element into the list may throw an exception
or it may succeed, at the option of the implementation. Such exceptions are
marked as "optional" in the specification for this interface.

Java Collection Framework - ListIterator Interface

The ListIterator interface extends the Iterator interface to support bi-directional


access as well as adding or removing or changing elements in the underlying
collection.

An iterator for lists that allows the programmer to traverse the list in either
direction, modify the list during iteration, and obtain the iterator's current position
in the list. A ListIterator has no current element; its cursor position always lies
between the element that would be returned by a call to previous() and the
element that would be returned by a call to next(). In a list of length n, there are
n+1 valid index values, from 0 to n, inclusive.

void add(int index, Object element)


Inserts the specified element at the specified position in this list
(optional operation).
boolean add(Object o)
Appends the specified element to the end of this list (optional
operation).
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of
this list, in the order that they are returned by the specified collection's
iterator (optional operation).
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list at the
specified position (optional operation).
void clear()
Removes all of the elements from this list (optional operation).
boolean contains(Object o)
Returns true if this list contains the specified element.
boolean containsAll(Collection c)
Returns true if this list contains all of the elements of the specified
collection.

boolean equals(Object o)
Compares the specified object with this list for equality.

Object get(int index)


Returns the element at the specified position in this list.

int hashCode()
Returns the hash code value for this list.

int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified
element, or -1 if this list does not contain this element.

boolean isEmpty()
Returns true if this list contains no elements.

Iterator iterator()
Returns an iterator over the elements in this list in proper sequence.

int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified
element, or -1 if this list does not contain this element.

ListIterator listIterator()
Returns a list iterator of the elements in this list (in proper sequence).

ListIterator listIterator(int index)


Returns a list iterator of the elements in this list (in proper sequence),
starting at the specified position in this list.

Object remove(int index)


Removes the element at the specified position in this list (optional
operation).

boolean remove(Object o)
Removes the first occurrence in this list of the specified element (optional
operation).

boolean removeAll(Collection c)
Removes from this list all the elements that are contained in the specified
collection (optional operation).

boolean retainAll(Collection c)
Retains only the elements in this list that are contained in the specified
collection (optional operation).
Object set(int index, Object element)
Replaces the element at the specified position in this list with the
specified element (optional operation).

int size()
Returns the number of elements in this list.

List subList(int fromIndex, int toIndex)


Returns a view of the portion of this list between the specified fromIndex,
inclusive, and toIndex, exclusive.

Object[] toArray()
Returns an array containing all of the elements in this list in proper
sequence.

Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in proper
sequence; the runtime type of the returned array is that of the specified
array.

The add (0) operation requires a little bit of explanation, also Adding an element
results in the new element being added immediately prior to the implicit cursor. This
calling previous after adding an element would return the new element and calling
next would have no effect, returning what would have been the next element prior to
the add operation.

Java Collection Framework - Map Interface

The Map interface is not an extension of Collection interface. Instead the


interface starts of it’s own interface hierarchy, for maintaining key-value
associations. The interface describes a mapping from keys to values, without
duplicate keys, by definition.

The Map interface provides three collection views, which allow a map's contents
to be viewed as a set of keys, collection of values, or set of key-value mappings.
The order of a map is defined as the order in which the iterator’s on the map's
collection views return their elements. Some map implementations, like the
TreeMap class, make specific guarantees as to their order; others, like the
HashMap class, do not.

void clear()
Removes all mappings from this map (optional operation).
boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
Set entrySet()
Returns a set view of the mappings contained in this map.
boolean equals(Object o)
Compares the specified object with this map for equality.
Object get(Object key)
Returns the value to which this map maps the specified key.
int hashCode()
Returns the hash code value for this map.
boolean isEmpty()
Returns true if this map contains no key-value mappings.
Set keySet()
Returns a set view of the keys contained in this map.
Object put(Object key, Object value)
Associates the specified value with the specified key in this map
(optional operation).
void putAll(Map t)
Copies all of the mappings from the specified map to this map
(optional operation).
Object remove(Object key)
Removes the mapping for this key from this map if it is present
(optional operation).
int size()
Returns the number of key-value mappings in this map.
Collection values()
Returns a collection view of the values contained in this map.
The interface methods can be broken down into three sets of operations:
altering, querying and providing alternative views.

The alteration operation allows you to add and remove key-value pairs from the
map. Both the key and value can be null. However you should not add a Map to
itself as a key or value.

Object put(Object key, Object value)


Object remove(Object key)
void putAll(Map t)
void clear()

The query operations allow you to check on the contents of the map
Object get(Object key)
boolean containsKey(Object key)
boolean containsValue(Object value)
int size()
boolean isEmpty()

The set methods allow you to work with the group of keys or values as a
collection
Set keySet()
Collection values()
Set entrySet()

Vous aimerez peut-être aussi