Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Collection
An object that groups multiple elements into a single unit such as
a Linked List or Stack
A collection is sometimes called a Container Class
Collections store, retrieve, and manipulate the elements they
contain
Collection Framework
A collections framework is a unified architecture for
representing and manipulating collections. The Java
Collections Framework contains the following:
Collections
Arrays
Linked Lists
Stacks
Queues
Trees
Collections
Arrays
Arrays
A sequential list of objects
Objects are located through an integer index
Has a fixed number of elements
Advantages
Disadvantages
Difficult to remove an element in the middle of the array (have to leave the
element null or compact the array after removing an element in the middle)
Difficult to add an element in the middle of the array (have to move existing
elements to make a hole in the array for the new element.
Fixed size means you may run out of space or use more memory than is
necessary
0
1
A 100
element
array
99
Collections
Linked List
Linked List
Set of nodes where each node has an object and a reference to the
next node.
Objects are located through an integer index
Advantages
Disadvantages
Searching can be difficult because there is no random access may have to
search through entire list to find what you are looking for
72.5
Collections
43.2
NULL
head
tail
67.1
The head points to the first node in the list, the tail
points to the last node in the list. A one-way linked
list is shown, but there is also a two-way linked list
(each node has a next and prev field, as well as the
data)
Stack
Stack
Objects are always added to and removed from the top of the list
LIFO data structure, Last In First Out
Operations: push (object onto stack), pop (object off the stack),
peek (at object on top of stack)
Advantages
Useful when LIFO access to data is desired (such as in compilers)
Disadvantages
Only have access to the element on the top of the stack (cant insert, remove,
or view elements in the middle of the stack)
push an
element onto
the stack
peek at the
top element
pop an
element off
the stack
top
Collections
Queue
Queue
Objects are always added to the end of the list and removed from
the front of the list FIFO data structure, First In First Out
Operations: enqueue (add object to end of list), dequeue (remove
object from front of list), front (examine object at front of the list)
Advantages
Useful when FIFO access to data is desired (such as waiting lists e.g.,
storing a set of tasks to be performed in the order they are received)
Disadvantages
Only have access to the first element (cant insert, remove, or view elements
in the middle of the queue)
enqueue an
element
front view
element at
front of list
dequeue an
element
front
front
Collections
new
front
Hash Table
Hash Table
Each object is converted into an integer hash code. The hash code
is used as an index into a table (which could be an array, linked list,
etc.)
Must resolve collisions usually each entry in the table has a
bucket (a linked list of objects with the same hash code)
Advantages
Very fast random access based on the hash code
Disadvantages
Requires good hash code or frequent collisions can turn fast access into a
linear search.
Each element
has an
associated hash
code
item
One solution to
collisions is to use
buckets
code
item
0
1
2
3
Example of generating a hash code into an array. Get hash code for the object,
then map it into the array space by taking the modulo (%):
Trees
Tree
Set of nodes organized as parents and children
Binary Trees Each node may have a most two children
B Trees No restrictions on number of children
Best for fast searches where additions/removals are infrequent
Advantages
Searching is very fast
Disadvantages
Collections
9
6
Maps
Map
A collection whose elements are pairs of keys and values
Objects are accessed/stored using a key value
Works well for matching strings or integers with objects (e.g., a
name with an Employee object or a product id with a Product
object)
Key
Bill Watson
Value
Employee
name: Bill Watson
id: 1598
ssn: 345-58-3717
salary: $65,000.00
Julia Devon
Employee
name: Julia Devon
id: 3487
ssn: 261-34-2156
salary: $72,500.00
Collections
Collection Interfaces
List
Set
Map
Queue
Provides support for queues and priority queues (queues ordered by priority)
Added in JDK 1.5 previously queues were supported with LinkedList
Collections
10
Allows duplicates
Users specify
location to store at
Use index to access
Collection
*
List
Linked List
No duplicates
No access by index
Set
Array List
Vector
HashSet
SortedSet
LinkedHashSet
Map
TreeSet
HashMap
SortedMap
LinkedHashMap
TreeMap
* = interface
Collections
11
Note that Lists have a special ListIterator which is-a Iterator that
has been customized for Lists it adds the following functions
void add(E: o)
Inserts the element into the list at the current iteration location
Boolean hasPrevious()
int nextIndex()
E previous()
void set(E: o)
Replaces the element at the current iteration location with the specified new
element
Collections
12
LinkedList
Another example of a List Collection is the LinkedList
class
public class LinkedListExample {
public static void main(String args[]) {
LinkedList<Employee> empList ;
Employee emp;
empList = new LinkedList<Employee>();
// Add an Employee to the List
emp = EmployeeReader.readEmployee();
emp = empList.add(emp);
// Some other ways of adding an Employee to a LinkedList
emp = empList.addFirst(emp);
emp = empList.addLast(emp);
emp = empList.add(5, emp);
}
}
Collections
13
Collections
14
Ordered Collection
Objects in the collection are sorted useful if you use an
Iterator
Underlying data structure is a Tree
E.g., classes TreeSet and TreeMap
Youll need a function that can compare two objects (are
two objects equal or is one object less than or greater than another
object?)
Collections
15
Unordered Map
LinkedHashMap
Unordered Maps use a Hash Table as the
underlying data structure
Maps do not have an add function they have a
put function instead
put(key, value)
Adds an entry with the specified key and value, or
replaces the value if an entry with the key already
exists
Collections
16
Collections
17
Your hashCode() function may return any integer value and will be
used to map onto the range of indices for the particular hash table
Follow these rules in writing your hash function:
Whenever it is invoked on the same object, the hashCode method must
consistently return the same integer
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: If x.equals(y), then x.hashCode() == y.hashCode()
It is OK for two objects that are not equal to have the same hash code
Write a hash function in a way that minimizes collisions
If you dont override the hashCode method, the default behavior is based on the
objects address almost certainly that will result in a bug
Collections
18
below.
If Employee ids are assigned in a way that results in many
class Employee {
private String firstName;
private String lastName;
private int id;
// Combine info in data members to produce hash code
public int hashCode() {
int code = id * 31;
code = code + firstName.hashCode() * 31;
code = code + lastName.hashCode();
return code;
}
public boolean equals(Object otherObj) {
}
}
Collections
19
Collections
20
Address
LinkedHashMap<Employee, Address>
To properly hash the key, override the hashCode() function
To find if the key is in a bucket, override the equals() function
class Employee {
private String name;
private int id;
public boolean equals(Object otherObj) {
Employee otherEmp;
if (!(otherObj instanceof Employee)) {
return false;
}
otherEmp = (Employee) otherObj;
return id == otherEmp.id;
}
public int hashCode() {
return id; // here we can use unique value as hash code
}
}
Collections
21
22
Collections
23
Unordered Set
LinkedHashSet
Unordered Sets are especially useful for removing
duplicates a common problem
Unordered Sets use a Hash Table as the
underlying data structure
Use the add function to add an element to the set
add(element)
o The element parameter is hashed (using hashCode())
to find the proper bucket to store it
A duplicate element will not be added to the set
o Checked by the equals() method
There
is no get function
Collections
24
a LinkedHashSet
Because the underlying data structure is a hash table, you need to override
the hashCode() function. The element will be hashed.
To determine if the element is in the bucket, equals() is used and must be
overridden
class Employee {
private String name;
private int id;
public boolean equals(Object otherObj) {
Employee otherEmp;
if (!(otherObj instanceof Employee)) {
return false;
}
otherEmp = (Employee) otherObj;
return id == otherEmp.id;
}
public int hashCode() {
return id; // here we can use unique value as hash code
}
}
Collections
25
Collections
Program Output
26
Collections
Program Output
27
Returns:
a set view of the keys contained in this map
Collections
28
Collections
29
Ordering Collections
Often we have a need to keep a Collection
ordered
E.g. employees ordered by name, salary, or social security
number
Collections
30
Ordering Collections
A TreeSet must be kept sorted. What does it use to order
31
Implementing Comparable
Example of implementing Comparable to be used for natural
ordering of elements
The Comparable interface is a commonly used interface that allows objects
to be compared for purposes of sorting.
class Employee implements Comparable<Employee> {
private String name;
private String socSecNum;
private int id;
private double salary;
public Employee(int newId) { id = newId; }
public int getId() { return id; }
public String toString() {
return "Employee: " + id;
}
// Return: -1 if object is less than parameter
//
0 if object is equal to parameter
//
+1 if object is greater than parameter
public int compareTo(Employee cmpEmp) {
if (id < cmpEmp.id) return -1;
if (id == cmpEmp.id) return 0;
return 1;
}
}
Collections
32
Using a TreeSet
We can create an ordered set of Employee objects using a
TreeSet
import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;
public class EmpSetTest {
public static void main(String args[]) {
Employee emp;
TreeSet<Employee> empSet;
Iterator<Employee> empIterator;
empSet = new TreeSet<Employee>();
emp = new Employee(1001);
empSet.add(emp);
emp = new Employee(2010);
empSet.add(emp);
emp = new Employee(1500);
empSet.add(emp);
empIterator = empSet.iterator();
while (empIterator.hasNext()) { // retrieve objects in order
emp = empIterator.next();
System.out.println(emp);
}
}
}
C: \collections>java EmpSetTest
Employee: 1001
Employee: 1500
Employee: 2010
Collections
Program Output
33
Collections
34
Collections
Program Output
35
Collections
Program Output
36
Collections
37
Obtaining Subsets
Given a starting point and an end point in a sorted set, we can
Collections
Program Output
38
Sorted Maps
Collections
39
Collections
40
41
Collections
42
Collections
43
return collections
static int binarySearch(List list, Object key)
Return index of element when found, or a value less than 0 if not found
static int binarySearch(List list, Object key, Compartor c)
Return index of element when found, or a value less than 0 if not found
static Object max(Collection c)
Find the largest element in the collection
static Object min(Collection c)
Find the smallest element in the collection
static void sort(List list)
Sorts a list
static void sort(List list, Comparator c)
Sort using the specified comparator
static void swap(List list, int i, int j)
Swap two elements in a list
static void copy(List dest, List src)
Copies elements of one list into another
static List unmodifiableList(List list)
Returns a view that is read-only useful for giving users internal lists that
they should not be able to change. Attempts to change result in a
UnsupportedOperationException
Collections
44