Collection Framework
- It is the standardized mechanism of grouping of the similar or different types of objects into a single object. This single object is known as collection framework.
- Aims/Characteristics of collection framework:
1) Performance: - It provides performance & when we want to transfer ‘n’ number
of records from the database to the main memory of the computer, keep all those ‘n’ number of records into a single
collection framework object and transfer if only one time.
2) Collection framework provides
EXTENDIBILITY. Arrays are also treated as collection framework objects but it
is fixed in its size & it allows us to place parallel type of elements. But
collection framework provides dynamic size & it allows us to add parallel
or different types of objects.
3) Adoptability: - Collection framework provides Adoptability features. Adoptability
is the process of adding one collection object at the end of another collection
object or at a specified position of another collection object.
4) Efficient & Effective: - C/F is by default efficient & effective in
organizing parallel or different types of objects in a single framework.
5) Algorithmic Concepts: - C/F by default provides algorithmic oriented
concepts & sorting techniques, searching techniques and preliminary data
structure concept like stack, queue & trees.
- One dimensional collection framework interfaces:
As a part of C/F we have following interfaces: -
1) java.util.Collection;
2) java.util.List;
3) java.util.SortedSet;
4) java.util.Queue;
- Hierarchy chart of 1-D Collection Framework:
java.util.Collection:
(1) Collection is an interface
which allows us to organize the data in a single object by accepting parallel
or different types of objects.
(2) Collection framework is
having the following features: -
(a) The interface Collection
is available at the top of the hierarchy of all collection framework
interfaces.
interfaces.
(b) Collection objects allow
us to add duplicates or duplicate elements.
(c) Collection object allows
us to insert an element at the end only.
(d) Collection object allows
us to insert an element at the end only.
(e) Collection object allows
us to retrieve the data only in the forward direction.
(f) Collection object
displays the data in that order in which order we have added.
java.util.List:
(1) The interface List extends
the Collection interface.
(2) An object of List allows us
to add duplicates of List.
(3) List objects allow us to add
element either at the end or at any specified position.
(4) List object allows us to
retrieve the data in forward direction, in backward direction & in random
direction.
(5) List object always displays
the data in sequential order.
java.util.Set:
(1) Set extends Collection
interface.
(2) Set object does not allow
duplicate elements.
(3) Set object allows us to add
an element at the end position only.
(4) Set object allows us to
retrieve the data in forward direction only.
(5) Set
object displays the
data in that order in which order we have added.
java.util.SortedSet:
(1) SortedSet extends Set
interface.
(2) An object of SortedSet does
not allows us to add duplicates of List
(3) SortedSet objects allow us
to add element either at the end position only .
(4) SortedSet object allows us
to retrieve the data in forward direction only.
(5) SortedSet object always
displays the data in sequential order.
- Methods in java.util.Collection:
1) public int size() : - This method is used to find
the number of elements of collection objects.
2) public boolean add(Object): - This method is used for
adding an object to the collection framework object.
a. As long as we call this
method to add the object to Collection Interface object & List Interface
object, this method returns true, since they allow duplicates.
b. When we call this method, by
Set Interface object & SortedSet Interface Object, for adding elements,
there is a possibility of returning false, since Set objects and SortedSet
objects do not allows dublicates.
3) public boolean
addAll(Collection): -This method is used for adding one collection object at the end of
another collection object. (called Adoptability)
4) public Iterator iterator() : - this method is used for
retrieving the objects from Collection Object, one by one.
Iterator is an Interface, which contains the
following methods:-
public
boolean hasNext()
public
Object next()
public boolean hasNext() : - This method is used for
determining weather the Iterator has next element or not. If it is having the
next element then it returns true, or else it returns false.
public Object next() : - This method is used for
obtaining the next element as long as hasNext() returns true.
- Methods in java.util.List : -
1) public void add(int, object): - This method is used for
adding the element at the specified position.
2) public void
addAll(int,Collection) : - This method is used for adding
one List object to the another List object at an specified position.
3) public Object get(int) : - This method is used for
retrieving an element of List by passing a valid position.
4) Public ListIterator
listIterator() : - This method is used for retrieving the elements of the List one by
one either in forward direction or in backward direction.
ListIterator is an interface
which contains the following methods: -
a) public boolean hasPrevious()
b) public Object previous()
Iterator is the base
interface for ListIterator.
hasPrevious() returns True,
if ListIterator Object is having previous element otherwise Fasle.
previous() is used for
obtaining previous element as long as hasPrevious returns true.
- Methods in java.util.Set:
This interface does not contain any
special methods except collection method
- Methods in java.util.SortedSet : -
1) public Object first(): - This method is used for
obtaining first Object in SortedSet.
2) public Object last(): - This method is used for
obtaining the last object in SortedSet.
3) public SortedSet
headset(Object obj): - This method is used to obtain
those objects which are less than or equal to
the target object.
4) public SortedSet
tailSet(Object obj) : - This method is used for obtaining those objects which are greater
than the target object.
5) public SortedSet
subset(Object obj1,Object obj2) : - This method is used for obtaining those objects
which are greater then or equal to the target object, obj1 & less than
target object , obj2.
Following are the classes and interfaces of the java.util package:
- Core Collection Interfaces:
(1) Collection
(2) Set
(3) SortedSet
(4) List
(5) Map
(6) SortedMap
- Concrete Implementation:
(1) ArrayList
(2) HashMap
(3) HashSet
(4) HashTable
(5) LinkList
(6) Properties
(7) Stack
(8) TreeMap
(9) TreeSet
(10)
Vector
(11)
WeakHashMap
- Abstract Implementaion : -
(1) AbstractCollection:
(2) AbstractList
(3) AbstractMap
(4) AbstractSequentialList
(5) AbstractSet
(6) Dictionary
o
Infrastructure Interface:
(1) Iterator
(2) ListIterator
(3) Comparable (java.lang)
(4) Comparator
o
Infrastructor
Classes:
(1) Collections
(2) Arrays
o
.Date & its
supporting Calendar Classes
o
Locale & its supporting ResourceBundle
classes
o
BitSet
o
Important additional interfaces:
(1) Enumeration
(2) Observer (and Observable
classes)
(3) EventListener
Java's Collection Framework
- A collections framework is a unified architecture for representing and manipulating collections. It has:
- Interfaces: abstract data types representing collections
- Implementations: concrete implementations of the collection interfaces
- Algorithms: methods that perform useful computations, such as searching and sorting
- These algorithms are said to be polymorphic: the same method can be used on different implementations
- An interface describes a set of methods:
- No constructors or instance variables
- Interfaces must be implemented by classes
- Classes guaranteed to have the same methods
- Objects can be treated as the same type
- Can use different algorithms / instance variables
Implementations:
- A collection class
- implements an ADT as a Java class
- implements all methods of the interface
- selects appropriate instance variables
- can be instantiated
- Java implements interfaces with
- List: ArrayList, LinkedList, Vector
- Map: HashMap, TreeMap
- Set: TreeSet, HashSet
Algorithms:
- Java has polymorphic algorithms to provide functionality for different types of collections
- Sorting (e.g. sort)
- Shuffling (e.g. shuffle)
- Routine Data Manipulation (e.g. reverse, addAll)
- Searching (e.g. binarySearch)
- Composition (e.g. frequency)
- Finding Extreme Values (e.g. max)
Two
Useful ADTs:
- List: a collection with a first element, a last element, distinct predecessors and successors
- duplicates that "equals" each other are allowed
- Map: maps keys to values
- Maps cannot contain duplicate keys
- Each key maps at most one value
List:
- A list is
- a collection of elements (numbers, strings, accounts, pictures,…)
- ordered (a sequence): there is a first, and a last element
- lists can be empty – no elements
- elements with a unique predecessor and successor
- also known as a sequence
o Peruse the Java 5 List Interface
ArrayList:
A Java Collection Class that Implements List.
- ArrayList:
- stores a collection of any type of object
- can be all the same type, or different types
- similar functionality to an array, but does not use subscripts
- is an indexed collection
- ArrayList JavaÔ: Resizable array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.
The size, isEmpty, get, set, iterator, and
listIterator operations run in constant time. The add operation runs in amortized
constant time, that is, adding n elements requires O(n) time. All of the other
operations run in linear time (roughly speaking). The constant factor is low
compared to that for the LinkedList implementation.
- List implemented by 3 classes:
// Interface name: List
// Three classes that implement the List interface:
List<String> bigList = new ArrayList<String>();
List<String> littleList = new
LinkedList<String>();
List<String> sharedList = new
Vector<String>();
// All three have an add method
bigList.add("in array list");
littleList.add("in linked list");
sharedList.add("in vector");
// All three have a get method
assertEquals("in array list",
bigList.get(0));
assertEquals("in linked list",
littleList.get(0));
assertEquals("in vector",
sharedList.get(0));
Generics:
- A List can be made to store only one type
List<BankAccount> accountList = new ArrayList<BankAccount>();
accountList.add(new BankAccount("One",
111.11));
accountList.add(new BankAccount("Two",
222.22));
accountList.add(new BankAccount("Three",
333.33));
accountList.add(new
BankAccount("Four", 444.44));
System.out.println(accountList.toString());
Output
[One $111.11, Two $222.22, Three $333.33, Four
$444.44]
Iterators:
- Iterators provide a general way to traverse all elements in a collection
ArrayList<String> list = new ArrayList<String>();
list.add("1-FiRsT");
list.add("2-SeCoND");
list.add("3-ThIrD");
Iterator<String>
itr = list.iterator();
while
(itr.hasNext()) {
System.out.println(itr.next().toLowerCase());
Output
1-first
2-second
3-third
Enhanced
for loop:
- If a class extends Iterable<E> (like you did with your Set<E> class), you can use Java's enhanced for loop of this general form
for (E refVar : collection<E> ) {
refVar
refers to each element in collection<E>
}
- Example
ArrayList<String> list = new
ArrayList<String>();
list.add("first");
for (String s : list)
System.out.println(s.toLowerCase());
Map
and SortedMap:
- The Map interface defines methods
- get, put, contains, keySet, values, entrySet
- TreeMap implements Map
- put, get, remove: O(log n)
- HashMap implements Map
- put, get, remove: O(1)
Set
and SortedSet:
- Some Map methods return Set
- The Set interface
- add, addAll, remove, size, but no get!
- Some implementations
- TreeSet: values stored in order, O(log n)
- HashSet: values in a hash table, no order, O(1)
Set up a small collection of mappings
Map<String, BankAccount> tm = new
TreeMap<String, BankAccount>();
tm.put("M", new BankAccount("Michel", 111.11));
tm.put("G", new
BankAccount("Georgie", 222.22));
tm.put("S", new
BankAccount("Sam", 333.33));
tm.put("P", new
BankAccount("Pei", 444.44));
tm.put("Z", new
BankAccount("Zac", 555.55));
// Coming up: Some Map methods
keySet()
// Get the set of keys in the Map.
// With
TreeMap, the keys are ordered.
Set<String> keys = tm.keySet();
assertEquals("[G, M, P, S, Z]",
keys.toString());
values()
// The values
Collection<BankAccount> accountCollection = tm.values();
Iterator<BankAccount> itr =
accountCollection.iterator();
double allTheMoney = 0.0;
while (itr.hasNext()) {
allTheMoney +=
itr.next().getBalance();
}
assertEquals(1666.65, allTheMoney, 0.01);
entrySet()
// The mappings
Collection<Entry<String, BankAccount>>
mapping =tm.entrySet();
Iterator<Entry<String, BankAccount>> itr2
=
mapping.iterator();
while (itr2.hasNext()) {
System.out.print("<"
+itr2.next().toString()+ ">
");
}
<G=Georgie $222.22> <M=Michel $111.11>
<P=Pei $444.44> <S=Sam $333.33> <Z=Zac $555.55>
Maps do not have an iterator.
No comments:
Post a Comment