Subsections
- In addition to the standard collection methods, the List interface allows for random access of elements through its get and set methods.
- List indices are zero based, so list.get(list.size())) is not a valid element.
List stuff = new ArrayList();
stuff.add("Apple");
stuff.add("Orange");
// what's the last item? Indexes are zero based!
System.out.println(stuff.get(stuff.size() - 1));
// change the first item to a pear.
stuff.set(0, "Pear");
// now iterate
Iterator it = stuff.iterator();
while(it.hasNext())
{
String item = (String)it.next();
System.out.println(item);
}
- ListIterator allows element addition, removal, and replacement during iteration.
- The java.util package provides two new List implementations: ArrayList and LinkedList.
- Vector is a legacy class retrofitted to the new Collection framework, and is thread safe.
- Maps associate the data elements in the collection with keys. The keys are derived from type Object, and may be different a type than the data. The get and put methods provide access to elements at a particular key.
Map userAges = new HashMap();
ages.put("John", new Integer(25));
ages.put("Nicole", new Integer(32));
ages.put("Bob", new Integer(43));
// How old is Bob?
Integer bobsAge = (Integer)userAges.get("Bob");
// if we have a user named Nicole, what's her age?
if(userAges.containsKey("Nicole"))
{
Integer nicolesAge = (Integer)userAges.get("Nicole");
}
- Caution: If the key object is mutable, take care not to change its value after using it in a Map.
- There are several Map implementations including HashMap and Hashtable.
- As a Java 1.1 legacy class, Hashtable is syncronized for thread safety.
- The java.util.Collections class provides standard utilities for Collections.
- List Sorting
- Binary List Search
- List reversing and shuffling
- Min and Max
- Synchonization
- Sorting makes use of the Comparator interface, which a programmer implements to determine how objects of a particular type are to be ordered.
- The Syncronization methods return thread-safe collections that are backed by a specified collection. Note that iteration is still not thread safe in this case.
|
|