0% found this document useful (0 votes)
0 views

Collection

The document provides an overview of Java 2 Collections, detailing the Collections Framework which includes interfaces, implementations, and algorithms for managing groups of objects. It explains the Collection and Iterator interfaces, highlighting their methods and functionalities, as well as the List and Set interfaces with their specific behaviors regarding order and uniqueness. Additionally, it discusses implementations like ArrayList and LinkedList, along with HashSet and TreeSet, emphasizing their performance characteristics and use cases.

Uploaded by

Parinaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Collection

The document provides an overview of Java 2 Collections, detailing the Collections Framework which includes interfaces, implementations, and algorithms for managing groups of objects. It explains the Collection and Iterator interfaces, highlighting their methods and functionalities, as well as the List and Set interfaces with their specific behaviors regarding order and uniqueness. Additionally, it discusses implementations like ArrayList and LinkedList, along with HashSet and TreeSet, emphasizing their performance characteristics and use cases.

Uploaded by

Parinaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Collections

Chapter 4
Java 2 Collections
• A collection is an object that groups multiple
elements into a single unit
• Very useful
» store, retrieve and manipulate data
» transmit data from one method to another
Collections Framework
• Unified architecture for representing and
manipulating collections.
• A collections framework contains three things
» Interfaces
» Implementations
» Algorithms
Collections Framework Diagram

•Interfaces, Implementations, and Algorithms


Collection Interface
• Defines fundamental methods
» int size();
» boolean isEmpty();
» boolean contains(Object element);
» boolean add(Object element); // Optional
» boolean remove(Object element); // Optional
» Iterator iterator();

• These methods are enough to define the basic


behavior of a collection
• Provides an Iterator to step through the elements in
the Collection
Iterator Interface
• The idea: Select each element in a collection
• Hide the underlying collection
Collection Iterator
isEmpty() hasNext()
add() List next()
remove()… remove()

• Iterators are fail-fast


• Exception thrown if collection is modified externally, i.e., not via the
iterator (multi-threading).
Iterator Interface
• Defines three fundamental methods
» Object next()
» boolean hasNext()
» void remove()
• These three methods provide access to the
contents of the collection
• An Iterator knows position within collection
• Each call to next() “reads” an element from the
collection
» Then you can use it or remove it
Iterator Position
Example - SimpleCollection
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
System.out.println(c.getClass().getName());
for (int i=1; i <= 10; i++) {
c.add(i + " * " + i + " = "+i*i);
}
Iterator iter = c.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}
}
List Interface Context

Collection

List
List Interface
• The List interface adds the notion of order to a
collection
• The user of a list has control over where an element is
added in the collection
• Lists typically allow duplicate elements
• Provides a ListIterator to step through the elements in
the list.
ListIterator Interface
• Extends the Iterator interface
• Defines three fundamental methods
» void add(Object o) - before current position
» boolean hasPrevious()
» Object previous()
• The addition of these three methods defines the basic
behavior of an ordered list
• A ListIterator knows position within list
Iterator Position - next(), previous()
ArrayList and LinkedList Context

Collection

List

ArrayList LinkedList
List Implementations
• ArrayList
» low cost random access
» high cost insert and delete
» array that resizes if need be
• LinkedList
» sequential access
» low cost insert and delete
» high cost random access
ArrayList overview
• Constant time positional access (it’s an array)
• ArrayList is an array based implementation where elements
• can be accessed directly via the get and set methods.
• Default choice for simple sequence.
import java.util.*;
public class Shuffle {
public static void main(String args[]) {
ArrayList l = new ArrayList();
for (int i = 0; i < args.length; i++)
l.add(args[i]);
System.out.println(l);
}
}
ArrayList methods
• The indexed get and set methods of the List interface are
appropriate to use since ArrayLists are backed by an array
» Object get(int index)
» Object set(int index, Object element)
• Indexed add and remove are provided, but can be costly if
used frequently
» void add(int index, Object element)
» Object remove(int index)
• May want to resize in one shot if adding many elements
» void ensureCapacity(int minCapacity)
LinkedList overview
• Stores each element in a node
• Each node stores a link to the next and previous nodes
• Insertion and removal are inexpensive
» just update the links in the surrounding nodes
• Linear traversal is inexpensive
• Random access is expensive
» Start from beginning or end and traverse each node while
counting
• LinkedList is 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
LinkedList entries
import java.util.*;
class ArrayLinkedListDemo {
public static void main(String args[])
{
LinkedList l1 = new LinkedList();
l1.add("A");
l1.add("B");
l1.add(new Integer(10));
System.out.println("The contents of list is " + l1);
l1.addFirst(“AA”);
l1.addLast("c");
l1.add(2,"D");
l1.add(1,"E");
l1.remove(3);
System.out.println("The contents of list is " + l1);
}
}
LinkedList methods
• The list is sequential, so access it that way
» ListIterator listIterator()
• ListIterator knows about position
» use add() from ListIterator to add at a position
» use remove() from ListIterator to remove at a position
• LinkedList knows a few things too
» void addFirst(Object o), void addLast(Object o)
» Object getFirst(), Object getLast()
» Object removeFirst(), Object removeLast()
Set Interface Context

Collection

Set
Set Interface
• Same methods as Collection
» different contract - no duplicate entries
• Defines two fundamental methods
» boolean add(Object o) - reject duplicates
» Iterator iterator()
• Provides an Iterator to step through the elements
in the Set
» No guaranteed order in the basic Set interface
» There is a SortedSet interface that extends Set
HashSet and TreeSet Context

Collection

Set

HashSet TreeSet
HashSet
• Find and add elements very quickly
» uses hashing implementation in HashMap
• Hashing uses an array of linked lists
» The hashCode() is used to index into the array
» Then equals() is used to determine if element is in the
(short) list of elements at that index
• No order imposed on elements
• The hashCode() method and the equals() method
must be compatible
» if two objects are equal, they must have the same
hashCode() value
TreeSet
• Elements can be inserted in any order
• The TreeSet stores them in order
» Red-Black Trees out of Cormen-Leiserson-Rivest
• An iterator always presents them in order
• Default order is defined by natural order
» objects implement the Comparable interface
» TreeSet uses compareTo(Object o) to sort
• Can use a different Comparator
» provide Comparator to the TreeSet constructor

You might also like