You are on page 1of 21

Collection

Framework

D.KARTHIK
18R21A1274

ALLPPT.com _ Free PowerPoint Templates, Diagrams and Charts


Collections Framework

A F r a m e w o r k is an extensive set of interfaces, abstract


classes and concrete classes together with support tools
Framework is provided in java.util package and comprises
three parts:
1. Core interfaces
2. Set of implementations.
3. Utility methods
Collection Interfaces

Collections are primarily defined through a set


of interfaces
 Supported by a set of that implement the
classes
interfaces
 Does not hold primitives, wrapper classes
use
can be specified using Generics
 Collections can be type i.e. type of
safe,
Example - Type Safe: elements
Collection<String> stringCollection = new
LinkedList<String>(); stringCollection.add(“GoodMorning’); -
Right stringCollection.add(8); - Wrong
Collection<Integer> integerCollection = new
LinkedList<Integer>(); integerCollection.add(10);
integerCollection.add(new Integer(12));
integerCollection.add(“hello”); -
General Purpose Implementations
Implementing Map Interface
Primary Classifications

Collections can be primarily grouped into four types


List – Lists of things
Sets – Unique things
Maps – Things with a unique ID
Queues – Things arranged by the order in
which they are to be processed
Above can be further classified into
Sorted
Unsorted
Ordered
Unordered
List Interface
Also called as sequence, is an ordered collection that can
contain duplicate elements.list indices are zero based.
One thing that list has and non-lists don’t have is a set of
methods related to index.
get(int index), indexOf(Object o), add(int index, Object obj)
Iterator Interface
Set Interface
Allows only unique elements

equals() methods determines whether two methods are identical

HashSet
- Uses hashcode of the inserted object, implemented using a hash table
- No ordering of elements
- add, remove and contains methods have constant time complexity

LinkedHashSet
- Ordered version of HashSet that maintains doubly linked list
-Useful in making set copies, such that original set’s iteration ordering
is preserved
TreeSet
-Sorted collection. Implemented using tree structure and guarantees ordering
of elements (natural order - ascending)
- add, remove and contains methods have logarithmic time complexity

Note: While using HashSet or LinkedHashSet, the objects added to them must
override hashCode().
Set Interface Ex.
Map Interface
Maps are similar to collections but are actually represented by
an entirely different class hierarchy
Map is an object that maps keys to values

Also called as Associative array or a dictionary


Depends on equals() method to determine whether two keys are
same or different . Keys cannot be duplicated.
- keySet() : returns a Set
Methods to retrieve key, values and key–value pair
- values() : returns a
- entrySet( Collection
) : returns a Set
Map Implementation
HashMap
- The implementation is based on a hash table.
- No ordering on (key, value) pairs – unsorted and
unordered
- Allows one null key and multiple null values
Hashtable
- Methods are synchronized
- Key or value cannot be null
LinkedHashMap
- Maintains insertion order.
-Provides fast iteration but slower in adding and
removing operation
TreeMap
-Sorted map. Sorted by natural order and also allows to
define custom sort order.
-Implementation based on tree structure. (key – value)
Map Example
Map<String,String> map = new
HashMap<String,String>(); map.put(“rama", "03-
9516743");
map.put(“Sita", "09-5076452");
map.put("Leo", "08-5530098");
map.put("Rita", "06-
8201124");
System.out.println(map);
//Iterating over key
for (String key :
map.keySet())
{System.out.println(key);}
//Iterating over key-value
pair
for (Map.Entry<String,String> entry: map.entrySet())
{ System.out.println(entry.getKey() + ": " +
entry.getValue());
Queue Interface
Queues support all of the standard Collection methods
Queue
Implementation :
Priority Queue:
-purpose is to create a “priority-in, priority out” queue as
opposed to FIFO queue.
-Elements are either ordered naturally or according
to Comparator
Queue<Integer> queue = new
LinkedList<Integer>(); queue.add(3);
queue.add(1);
queue.add(new
Integer(1));
queue.add(new
Integer(6));
queue.remove();
System.out.println(queue)
use of word Collection
collection (lowercase c), which represents any of the data
structures in which objects are stored and iterated over.
 Collection (capital C), which is actually the
interface from which Set, List, and Queue extend. (That's
java.util.Collection
right, extend, not implement. There are no direct
implementations of Collection.)
Collections (capital C and ends with s) is the java.util.Collections
class that holds a pile of static utility methods for use with
collections.
Sorting Collections
import
java.util. ;
class TestSort1 {
public static
void
main(String[]
args) {
ArrayList<String> stuff = new
ArrayList<String>(); stuff.add("Denver");
stuff.add("Boulder");
stuff.add("Vail");
stuff.add("Aspen");
stuff.add("Telluride");
System.out.println("unsorted " +
stuff); Collections.sort(stuff);
System.out.println("sorted " + stuff);
}
}
Comparable interface
an example – MusicList
Used by Collections.sort() method and Arrays.sort() to sort
lists and arrays respectively.
Only one sort sequence can be created

CompareTo() method should be implemented


int x = thisObject.compareTo(anotherObject); returns negative, positive or
zero
value

Ex:

Class MusicInfo implements Comparable< MusicInfo


> { String title;
// existing code
public int compareTo(MusicInfo d)
{ return title.
Compare.To(d.getTitle());
} }
Comparator Interface
The Comparator interface provides the capability to sort a
given collection any number of different ways.
Can be used to sort instances of any class
Easy to implement and has a method compare()
Example

import java.util. ;
class GenreSort implements Comparator<DVDInfo>
{ public int compare(DVDInfo one, DVDInfo
two) {
return
one.getGenre().compareTo(two.getGenre());
}
}
Comparator vs Comparable

Comparable Comparator
int objOne.compareTo(objTwo) int compare(objOne, objTwo)

Returns Same as Comparable


negative if objOne < objTwo
zero if objOne == objTwo
positive if objOne > objTwo

You must modify the class whose You build a class separate from the
instances you want to sort. class whose instances you
want to sort.

Only one sort sequence can be created Many sort sequences can be
created
Implemented by String, Wrapper classes, Date, etc
Implemented by third party
classes
Searching Arrays and Collections
Certain rules apply while searching
1.Searches are performed using the binarySearch() method.
2. Successful searches return the int index of the element
being searched.
3. Unsuccessful searches return an int index that represents
the
insertion point.
4.The collection/array being searched must be sorted before
you can search it.
5.If you attempt to search an array or collection that has
not already been sorted, the results of the search will not be
predictable.
6.If the collection/array you want to search was sorted
in natural order, it must be searched in natural order.
7.If the collection/array you want to search was sorted using
a Comparator, it must be searched using the same Comparator,
which is passed as the second argument to the binarySearch()
method. Remember that Comparators cannot be used when searching

You might also like