Professional Documents
Culture Documents
Collections & Generics
Collections & Generics
TOPICS
◼ Iterator
◼ Collection Framework
◼ Collections
◼ Lists
◼ Maps
◼ Generics
◼ Lists Implementation
COLLECTIONS
COLLECTIONS INTRODUCTION
• Collections are container abstractions that allow you to aggregate a group (collection) of objects
implementation-independent manner
• Can be not-modifiable
HOW COLLECTIONS ARE USED
Iterable
Collection Map
SortedSet
INTERFACE ITERABLE
◼ What’s an iterator?
◼ It provides methods for visiting (forward direction only) and removing elements of a collections:
◼ boolean hasNext();
◼ T next();
◼ void remove();
COLLECTION ABSTRACTIONS
Collection is the root interface of the collections framework, declaring basic operations such as:
◼ add(E e) to add elements to the collection
◼ contains(Object key) to determine whether the collection contains key
◼ isEmpty() to test the collection for emptiness
◼ iterator() to get an interator over the elements of the collection
◼ remove(Object o) to remove a single instance of o from the collection, if present
◼ size() to find out the number of elements in the collection
None of the collection implementations in the Java library implement Collection directly. Instead they implement List
or Set.
THE COLLECTION INTERFACE - OPERATIONS
public interface Collection
{
// Basic Operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element); // Optional
boolean remove(Object element); // Optional
Iterator iterator();
// Bulk Operations
boolean containsAll(Collection c);
boolean addAll(Collection c); // Optional
boolean removeAll(Collection c); // Optional
boolean retainAll(Collection c); // Optional
void clear(); // Optional
// Array Operations
Object[] toArray();
Object[] toArray(Object a[]);
}
LISTS
The List interface extends the Collection interface to represent ordered collections, or sequences. List has
◼ methods for positional (indexed) access to elements
◼ add(int, Object)
◼ get(int index)
◼ indexOf(Object o)
◼ remove(int index)
◼ set(int index, E element)) //replace method
◼ Methods for searching
◼ indexOf(Object)
◼ lastIndexOf(Object)
◼ a special iterator, ListIterator
◼ that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator
interface provides; and methods to obtain a ListIterator
◼ Extraction for sublist
◼ subList(int fromIndex, int toIndex) that returns a view of a portion of the list.
LIST
◼ ArralyList and LinkedList are the two basic List implementations provided in the Java standard library.
◼ Both implement the List interface.
◼ ArrayList
◼ Array based implementation
◼ Elements can be accessed directly via the get and set methods
◼ Default choice for simple sequence
◼ LinkedList
◼ Based on a double linked list
◼ Gives better performance on add and remove compared to ArrayList
◼ Gives poorer performance on get and set methods compared to ArrayList
ARRAYLIST
◼ – e.g., ClassCastException
◼ » Note: there are ways to get around this, but the code is clumsy
• There had to be a better way: enter generics
SUMMARY
◼ Array
◼ Holds objects of known type.
◼ Fixed size.
◼ Collections
◼ Generalization of the array concept.
◼ Set of interfaces defined in Java for storing object.
◼ Multiple types of objects.
◼ Resizable.
◼ Major changes to in Java 5
◼ Introduced generics
MAP INTERFACE
• The Map interface allows you to store/retrieve objects by keys (lookup names)
– so the map consists of keyword / value pairs
• the keyword is the lookup name
• the value is the object placed/retrieved in/from the map
• You declare/parameterize a Map with the types of objects you intend to use with the map
– the order will vary based on the implementing class you use. if you swap impls, the order could be different
• So, if the sorting of keys is important in your application, use the SortedMap interface
◼ Core Operations
– boolean clear();
– boolean containsKey(K key);
– boolean containsValue(V value);
– V get(K key) Where K and V are generic types that are parameterized with
– boolean isEmpty(); actual types at the point of instantiation
– Set<key> keySet();
– V put (K key, V value);
– V remove (Object key)
– int size();
MAP INTERFACE
• The map’s key must be unique for each value placed in the map
• Suppose we wanted to create a customer map using ssn as the keyword; then to
{
msgQueue.add(msg);
}
GENERICS
GENERICS
◼ Supply a type argument in the angle brackets. Read ArrayList<string> as “ArrayList of String”
ArrayList<string> strings = new ArrayList<string>();
strings.add("Helluva");
strings.add("Engineer!");
◼ If we try to add an object that isn’t a String, we get a compile error:
Integer BULL_DOG = Integer.MIN_VALUE;
strings.add(BULL_DOG); // Won’t compile
◼ With a typed collection, we get autoboxing on insertion and retrieval:
ArrayList ints = new ArrayList<>();
ints.add(42);
int num = ints.get(0);
◼ Notice that we didn’t need to supply the type parameter in the creation expression above. Java inferred the type parameter from the declaration.
(Note: this only works in Java 7 and above.)
ARRAYS
ARRAYS
◼ Advantages
◼ Knows the type it holds, i.e., compile-time type checking
◼ Knows its size, i.e., ask for the length
◼ Can hold primitive types directly
◼ Automatic boundary checking, raises exceptions if violated
◼ Disadvantages
◼ Only hold one type of objects (including primitives)
◼ Fixed size