SlideShare uma empresa Scribd logo
1 de 72
Topics
• What is and Why Collections?
• Core Collection Interfaces
• Implementations
• Algorithms
• Custom Implementations
• Interoperability
TheAndroid-mania.com
What is a Collection?
• A “collection” object — sometimes called a container
— is simply an object that groups multiple elements
into a single unit.
• Collections are used to store, retrieve, manipulate,
and communicate aggregate data
> Typically, they represent data items that form a natural group,
such as a poker hand (a collection of cards), a mail folder (a
collection of letters), or a telephone directory (a mapping of
names to phone numbers).
TheAndroid-mania.com
What is a Collection Framework?
• A collections framework is a unified architecture for
representing and manipulating collections
• All collections frameworks contain the following:
> Interfaces
> Implementations
> Algorithms
TheAndroid-mania.com
Benefits of Collection Framework
• Reduces programming effort
• Increases program speed and quality
• Allows interoperability among unrelated APIs
> The collection interfaces are the vernacular by which APIs
pass collections back and forth
• Reduce effort to learn and use new APIs
• Reduces effort to design new APIs
• Fosters software reuse
> New data structures that conform to the standard collection
interfaces are by nature reusable
TheAndroid-mania.com
Interfaces
and
implementation
in Collection Framework
TheAndroid-mania.com
Interfaces
• Collection interfaces are abstract data types that
represent collections
> Collection interfaces are in the form of Java interfaces
• Interfaces allow collections to be manipulated
independently of the implementation details of their
representation
> Polymorphic behavior
• In Java programming language (and other objectoriented languages),
interfaces generally form a
hierarchy
> You choose one that meets your need as a type
TheAndroid-mania.com
Implementations
• These are the concrete implementations of the collection
interfaces.
TheAndroid-mania.com
Types of Implementations
• General-purpose implementations
• Special-purpose implementations
• Concurrent implementations
• Wrapper implementations
• Convenience implementations
• Abstract implementations
TheAndroid-mania.com
Implementations
• Implementations are the data objects used to store
collections, which implement the interfaces
• Each of the general-purpose implementations (you
will see in the following slide) provides all optional
operations contained in its interface
• Java Collections Framework also provides several
special-purpose implementations for situations that
require nonstandard performance, usage
restrictions, or other unusual behavior
TheAndroid-mania.com
General Purpose Implementations
interfaces Implementations
Hash Table Resizable
Array
Tree Linked List HashTbale
+ Linked List
Set Hash Set Tree Set Linked Hash
Set
List Array List Linked List
Queue
Map Hash Map Tree Map Linked Hash
Map
TheAndroid-mania.com
Algorithms
• These are the methods that perform useful
computations, such as searching and sorting, on
objects that implement collection interfaces
• The algorithms are said to be polymorphic: that is,
the same method can be used on many different
implementations of the appropriate collection
interface
> In essence, algorithms are reusable functionality.
TheAndroid-mania.com
Core Collection interfaces
TheAndroid-mania.com
Core Collection Interfaces Hierarchy
Collection
Set List Queue
Sorted
Set
Map
Sorted Map
TheAndroid-mania.com
Core Collection Interfaces
• Core collection interfaces are the foundation of the
Java Collections Framework
• Core collection interfaces form a inheritance
hierarchy among themselves
> You can create a new Collection interface from them (highly likely
you don't have to)
TheAndroid-mania.com
“Collection” interface
TheAndroid-mania.com
“Collection” Interface
• The root of the collection hierarchy
• Is the least common denominator that all collection
implement
> Every collection object is a type of Collection interface
• Is used to pass collection objects around and to
manipulate them when maximum generality is
desired
> Use Collection interface as a type
• JDK doesn't provide any direct implementations of
this interface but provides implementations of more
specific sub interfaces, such as Set and List.
TheAndroid-mania.com
“Collection” Interface (Java SE 5)
public interface Collection<E> extends Iterable<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array operations
Object[] toArray(); TheAndroid-mania.com
Example
 import java.util.*;
 import java.util.Collection;
 public class collectioninterface {
 public static void main(String[] args) {
 Collection collection = new ArrayList();
 collection.add("Dev");
 collection.add("Manuals");
 System.out.print(" Elements Of the Array List are ");
 System.out.print(collection + ".");
 }
 }
TheAndroid-mania.com
add() and remove() methods of
Collection Interface
• The add() method is defined generally enough so
that it makes sense for collections that allow
duplicates as well as those that don't
• It guarantees that the Collection will contain the
specified element after the call completes, and
returns true if the Collection changes as a result of
the call.
> add() method of Set interface follows “no duplicate” rule
TheAndroid-mania.com
Collection
Interface
Traversing
TheAndroid-mania.com
Two Schemes of Traversing
Collections
• for-each
> The for-each construct allows you to concisely traverse a
collection or array using a for loop
for (Object o: collection)
System.out.println(o);
• Iterator
> An Iterator is an object that enables you to traverse through a
collection and to remove elements from the collection
selectively, if desired
TheAndroid-mania.com
Iterator
Iterator means an Object with which we can travel all through a range
of elements.
It works like a Pointer. In database, Sometimes Iterator is called a
Cursor.
Class signature : Public interface Iterator
Enumeration interface is replaced by iterator in collections frame
work.the advantages over Enumerations:
Iterator allow the caller to remove elements from the underlying
collection during the iteration with well-defined semantics.
Method name have been improved.
We can print from any index number , but need not all the elements.
TheAndroid-mania.com
Iterator Interface
public interface Iterator {
boolean hasNext();
Object next();
void remove(); //optional
}
• hasNext() method returns true if the iteration has more elements
• next() method returns the next element in the iteration
• remove() is the only safe way to modify a collection during
iteration; the behavior is unspecified if the underlying collection is
modified in any other way while the iteration is in progress
TheAndroid-mania.com
Use Iterator over for-each when you need
to
• Remove the current element
> The for-each construct hides the iterator, so you cannot call
remove
> Therefore, the for-each construct is not usable for filtering.
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
• Iterate over multiple collections in parallel
TheAndroid-mania.com
List Iterator Interface
List iterator is an interface that contains methods to retrieve the
elements from a collection object, both in forward and reverse
directions.
It has following methods:
boolean hasNext(); returns true if the List Iterator has more elements when
traversing the list in the forward direction.
boolean hasPrevious(); returns true if the List Iterator has more elements when
traversing the list in the reverse direction.
element next(); returns the next element.
element previous(); returns the previous element in the list.
void remove(); removes from the list the last element that was returned.
TheAndroid-mania.com
List Interfaces
and
Implementation
TheAndroid-mania.com
“List” Interface
• An ordered collection (sometimes called a
sequence)
• Lists can contain duplicate elements
• The user of a List generally has precise control over
where in the list each element is inserted and can
access elements by their integer index (position)
> If you've used Vector, you're already familiar with the general basics
of List
TheAndroid-mania.com
Additional Operations Supported by
“List” Interface over “Collection”
• Positional access — manipulates elements based
on their numerical position in the list
• Search — searches for a specified object in the list
and returns its numerical position
• Iteration — extends Iterator semantics to take
advantage of the list's sequential nature
• Range-view — performs arbitrary range operations
on the list.
TheAndroid-mania.com
“List” Interface
public interface List<E> extends Collection<E> {
// Positional access
E get(int index);
E set(int index, E element); //optional
boolean add(E element); //optional
void add(int index, E element); //optional
E remove(int index); //optional
boolean addAll(int index,
Collection<? extends E> c); //optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// Range-view TheAndroid-mania.com
Implementations of “List” Interface
• ArrayList
> Offers constant-time positional access
> Fast
> Think of ArrayList as Vector without the synchronization
overhead
> Most commonly used implementation
• LinkedList
> Use it you frequently add elements to the beginning of the List
or iterate over the List to delete elements from its interior
TheAndroid-mania.com
“Array List”
ArrayList is a Sub class of AbstractList and implements List.
Signature:
Array List includes a feature called Dynamic Arrays-memory is
dynamically allotted and re-allotted to accommodate all the
elements.
Array list is not Synchronised.
public class ArrayList extends AbstractList implements List, Cloneable,Serializable
TheAndroid-mania.com
Array List Examples
import java.util.*;
public class IteratorArrayList{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Integer(10));
al.add(new Double(25.5));
al.add(new Boolean(false));
al.add(new String("santhosh"));
al.add(new StringBuffer("Trainer"));
al.add(new Date());
Iterator it=al.iterator();
while(it.hasNext()){
Object obj=it.next();
System.out.println(obj);
if(obj instanceof Number)
{
it.remove();
}
} TheAndroid-mania.com
Linked List
A linked List contains a group of elements in the form of nodes.
Each node will have 3 fields
Data Field contains data
And
the two Link fields contain references to previous and next nodes.
Linked List is very convenient to store data. Inserting the elements
into the linked list and removing the elements from the linked list is
done quickly and takes the same amount of time.
TheAndroid-mania.com
Set Interface
and
Implementation
TheAndroid-mania.com
“Set” Interface
• A collection that cannot contain duplicate elements
• Models the mathematical set abstraction and is used
to represent sets
> cards comprising a poker hand
> courses making up a student's schedule
> the processes running on a machine
• The Set interface contains only methods inherited
from Collection and adds the restriction that
duplicate elements are prohibited.
TheAndroid-mania.com
“Set” Interface (Java SE 5)
public interface Set<E> extends Collection<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array Operations
Object[] toArray(); TheAndroid-mania.com
“Sorted Set” Interface
• A Set that maintains its elements in ascending order.
Several additional operations are provided to take
advantage of the ordering
• Sorted sets are used for naturally ordered sets, such
as word lists and membership roll.
TheAndroid-mania.com
Implementations of “Set”
Interface
Implementations of “Set” Interface
• HashSet
• TreeSet
• LinkedHashSet
TheAndroid-mania.com
HashSet
• HashSet is much faster than TreeSet (constant time versus log-time
for most operations) but offers no ordering guarantees
• Mostly commonly used implementation.
Caveats of Using HashSet
• Iteration is linear in the sum of the number of entries and the number
of buckets (the capacity).
> Choosing an initial capacity that's too high can waste both
space and time.
> Choosing an initial capacity that's too low wastes time by copying the
data structure each time it's forced to increase its capacity.
TheAndroid-mania.com
Example for HashSet
import java.util.*;
public class HashSetinfo{
public static void main(String args[]){
HashSet hs=new HashSet();
Integer il=new Integer(10);
hs.add(il);
Double d1=new Double(10.5);
hs.add(d1);
hs.add(new Integer(20));
hs.add("Santhosh Teleman");
hs.add(new String("Trainer"));
System.out.println("Number of elements"+hs.size());
System.out.println("il exists:"+hs.contails(il));
System.out.println("Elements before remeoval");
System.out.println(hs);
hs.remove(d1);
System.out.println("elements after remeoval");
System.out.println(hs);
TheAndroid-mania.com
TreeSet
• When you need to use the operations in the SortedSet interface, or if
value-ordered iteration is required.
This class guarantees that the sorted set will be in ascending element
order,sorted according to to the natural order of the elements.
To optimize TreeSet and HashSet space usage, we can start with less
initial capacity and load capacity.
Class Signature:
public class TreeSet extends AbstractSet implements SortedSet ,Cloneable,
Serializable
TheAndroid-mania.com
Example: Set Interface & TreeSet
Import java.util.*;
Public Class TreeSet{
public static void main(String[] args) {
Set ts = new TreeSet();
ts.add("one");
ts.add("two");
ts.add("three");
ts.add("four");
ts.add("three");
System.out.println("Members from TreeSet = " + ts);
}
Result: Members from TreeSet = [four, one, three, two]
TheAndroid-mania.com
LinkedHashSet
• Implemented as a hash table with a linked list running through it
• Provides insertion-ordered iteration (least recently inserted to most
recently) and runs nearly as fast as HashSet.
• Spares its clients from the unspecified, generally chaotic ordering
provided by HashSet without incurring the increased cost associated
with TreeSet.
TheAndroid-mania.com
Example: Set Interface & LinkedHashSet
Import java.util.*;
public class LinkedHashSet{
public static void main(String[] args) {
Set ts2 = new LinkedHashSet();
ts2.add(2);
ts2.add(1);
ts2.add(3);
ts2.add(3);
System.out.println("Members from LinkedHashSet = " + ts2);
}
}
Result: Members from LinkedHashSet = [2, 1, 3]
TheAndroid-mania.com
Example: Set Interface & HashSet
public class Main {
public static void main(String[] args) {
Set s = new HashSet(); // Order is not guaranteed
MyOwnUtilityClass.checkDuplicate(s, args);
s = new TreeSet(); // Order according to values
MyOwnUtilityClass.checkDuplicate(s, args);
s = new LinkedHashSet(); // Order according to insertion
MyOwnUtilityClass.checkDuplicate(s, args);
}
}
TheAndroid-mania.com
Example: Set Interface & HashSet
The numbers are added in the following order
2
3
4
1
2
Set type = java.util.HashSet [3, 2, 4, 1]
Set type = java.util.TreeSet [1, 2, 3, 4]
Set type = java.util.LinkedHashSet [2, 3, 4, 1]
TheAndroid-mania.com
Map interface
and
Implementation
TheAndroid-mania.com
“Map” Interface
• Handles key/value pairs.
• A Map cannot contain duplicate keys; each
key can map to at most one value.
If you've used Hash table, you're already
familiar with the basics of Map.
Class Signature:
public interface map
TheAndroid-mania.com
“Map” Interface (Java SE 5)
public interface Map<K,V> {
// Basic operations
V put(K key, V value);
V get(Object key);
V remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
// Bulk operations
void putAll(Map<? extends K, ? extends V> m);
void clear();
// Collection Views
public Set<K> keySet();
public Collection<V> values();
public Set<Map.Entry<K,V>> entrySet();
// Interface for entrySet elements
public interface Entry {
TheAndroid-mania.com
“Sorted Map” Interface
• A Map that maintains its mappings in ascending key
order
> This is the Map analog of Sorted Set.
• Sorted maps are used for naturally ordered
collections of key/value pairs, such as dictionaries
and telephone directories.
TheAndroid-mania.com
Implementations of “Map” Interface
• Hash Map
> Use it you want maximum speed and don't care about iteration
order.
> Most commonly used implementation
• Tree Map
> Use it when you need Sorted Map operations or key-ordered
Collection-view iteration
• Linked HashMap
> Use if you want near-Hash Map performance and insertion order
iteration
TheAndroid-mania.com
Hash Map
HashMap is like Hashtable which stores key/value pairs. It implements
map interface and we can use all the operations (methods) of map
interface.
It permits null values and the null key.
Hash map is almost equivalent to HashTable, except that it is un-
synchronised and permits nulls.
Order of elements is not guaranteed.
Class signature:
public class Hashmap extends AbstractMap implements
Map,Cloneable,Serializable
TheAndroid-mania.com
Tree map
This class extends AbstractMap and implements SortedMap.
This class Guarantees that the elements will be in ascending key order,
sorted according to the natural order based on the keys.
Class signature:
public class Treemap extends AbstractMap implements SortedMap ,
Cloneable, Serializable
TheAndroid-mania.com
Queue interface
and
implementation
TheAndroid-mania.com
“Queue” Interface
• A collection used to hold multiple elements prior to
processing
• Besides basic Collection operations, a Queue
provides additional insertion, extraction, and
inspection operations
• Typically, but do not necessarily, order elements in a
FIFO (first-in, first-out) manner.
TheAndroid-mania.com
Implementations of Queue
Interface
• General purpose Queue implementations
> LinkedList implements the Queue interface, providing FIFO
queue operations for add, poll, and so on
> PriorityQueue class is a priority queue based on the heap
data structure
> This queue orders elements according to an order specified at
construction time, which can be the elements' natural ordering
or the ordering imposed by an explicit Comparator.
• Concurrent Queue implementations
TheAndroid-mania.com
Convenience Implementations
TheAndroid-mania.com
Collections Class
• Provides methods to return the empty Set, List, and
Map — emptySet, emptyList, and emptyMap.
> The main use of these constants is as input to methods that
take a Collection of values when you don't want to provide
any values at all
> tourist.declarePurchases(Collections.emptySet());
• Provides methods for sorting and shuffling
> Collections.sort(l);
> Collections.shuffle(l);
TheAndroid-mania.com
Abstract Classes
TheAndroid-mania.com
Abstract Classes
• Includes abstract implementations
> AbstractCollection
> AbstractSet
> AbstractList
> AbstractSequentialList
> AbstractMap
• To aid in custom implementations
> Reduces code you have to write
TheAndroid-mania.com
Algorithms
TheAndroid-mania.com
Algorithms
• Sorting
• Shuffling
• Routine data manipulation
• Searching
• Composition
• Find extreme values
TheAndroid-mania.com
Algorithms
• Provided as static methods of Collections class
• The first argument is the collection on which the
operation is to be performed
• The majority of the algorithms provided by the Java
platform operate on List instances, but a few of them
operate on arbitrary Collection instances
TheAndroid-mania.com
Sorting
• The sort algorithm reorders a List so that its
elements are in ascending order according to an
ordering relationship
• Two forms of the operations
> takes a List and sorts it according to its elements' natural
ordering
> takes a Comparator in addition to a List and sorts the
elements with the Comparator
TheAndroid-mania.com
Natural Ordering
• The type of the elements in a List already implements
Comparable interface
• Examples
> If the List consists of String elements, it will be sorted into
alphabetical order
> If it consists of Date elements, it will be sorted into chronological
order
> String and Date both implement the Comparable interface.
Comparable implementations provide a natural ordering for a class,
which allows objects of that class to be sorted automatically
• If you try to sort a list, the elements of which do not
implement Comparable, Collections.sort(list) will throw a
ClassCastException.
TheAndroid-mania.com
Sorting by Natural Order of List
// Set up test data
String n[] = {
new String("John"),
new String("Karl"),
new String("Groucho"),
new String("Oscar")
};
// Create a List from an array
List l = Arrays.asList(n);
// Perform the sorting operation
Collections.sort(l);
TheAndroid-mania.com
Sorting by Comparator
Interface
• A comparison function, which imposes a total
ordering on some collection of objects
• Comparators can be passed to a sort method (such
as Collections.sort or Arrays.sort) to allow precise
control over the sort order
• Comparators can also be used to control the order
of certain data structures (such as sorted sets or
sorted maps), or to provide an ordering for
collections of objects that don't have a natural
Ordering.
TheAndroid-mania.com
Sorting by Natural Order of List
// Set up test data
ArrayList u2 = new ArrayList();
u2.add("Beautiful Day");
u2.add("Stuck In A Moment You Can't Get Out Of");
u2.add("Elevation");
u2.add("Walk On");
u2.add("Kite");
u2.add("In A Little While");
u2.add("Wild Honey");
u2.add("Peace On Earth");
u2.add("When I Look At The World");
u2.add("New York");
u2.add("Grace");
Comparator comp = Comparators.stringComparator();
Collections.sort(u2, comp); TheAndroid-mania.com
Shuffling
• The shuffle algorithm does the opposite of what sort does, destroying
any trace of order that may have been present in a List
> That is, this algorithm reorders the List based on input from a
source of randomness such that all possible permutations occur with
equal likelihood, assuming a fair source of randomness
• Useful in implementing games of chance
> could be used to shuffle a List of Card objects representing a
deck
> generating test cases
TheAndroid-mania.com
Routine Data Manipulation
• The Collections class provides five algorithms for doing routine data
manipulation on List objects
> reverse — reverses the order of the elements in a List.
> fill — overwrites every element in a List with the specified value.
This operation is useful for reinitializing a List.
> copy — takes two arguments, a destination List and a source List, and copies
the elements of the source into the destination, overwriting its contents. The
destination List must be at least as long as the source. If it is longer, the
remaining elements in the destination List are unaffected.
> swap — swaps the elements at the specified positions in a List.
> addAll — adds all the specified elements to a Collection. The elements to be
added may be specified individually or as an array.
TheAndroid-mania.com
Searching
• The Collections class has binarySearch() method for
searching a specified element in a sorted List
// Set up testing data
String name[] = {
new String("Sang"),
new String("Shin"),
new String("Boston"),
new String("Passion"),
new String("Shin"),
};
List l = Arrays.asList(name);
int position = Collections.binarySearch(l, "Boston");
System.out.println("Position of the searched item = " + position);
TheAndroid-mania.com
Composition
• Collections.frequency(l) — counts the number of
times the specified element occurs in the specified
collection
• Collections.disjoint(l1, l2) — determines whether two
Collections are disjoint; that is, whether they contain
no elements in common. The Collections class has
binarySearch() method for searching a specified
element in a sorted List.
TheAndroid-mania.com

Mais conteúdo relacionado

Mais procurados

Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google CollectionsAndré Faria Gomes
 
Java Collections Framework
Java  Collections  FrameworkJava  Collections  Framework
Java Collections Frameworkguestd8c458
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Java class 5
Java class 5Java class 5
Java class 5Edureka!
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialMarcus Biel
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternNitin Bhide
 

Mais procurados (20)

Java util
Java utilJava util
Java util
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 
Java Collections Framework
Java  Collections  FrameworkJava  Collections  Framework
Java Collections Framework
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java class 5
Java class 5Java class 5
Java class 5
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Java collection
Java collectionJava collection
Java collection
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Java collections
Java collectionsJava collections
Java collections
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java collection
Java collectionJava collection
Java collection
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video Tutorial
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 

Destaque

Lenguaje oral, primera tecnologia
Lenguaje oral, primera tecnologiaLenguaje oral, primera tecnologia
Lenguaje oral, primera tecnologia1804power
 
Mapa de ruta directores. insc. inicial 2015
Mapa de ruta  directores. insc. inicial 2015Mapa de ruta  directores. insc. inicial 2015
Mapa de ruta directores. insc. inicial 2015ctepay
 
Etapas (para directores e inspectores inicial) de la inscripción condicional ...
Etapas (para directores e inspectores inicial) de la inscripción condicional ...Etapas (para directores e inspectores inicial) de la inscripción condicional ...
Etapas (para directores e inspectores inicial) de la inscripción condicional ...ctepay
 
Cc 5 14-13 - animals services snap adoption subsidy-presentation
Cc 5 14-13 - animals services snap adoption subsidy-presentationCc 5 14-13 - animals services snap adoption subsidy-presentation
Cc 5 14-13 - animals services snap adoption subsidy-presentationCity of San Angelo Texas
 
Dados da Composição dos Produtos 4Life
Dados da Composição dos Produtos 4LifeDados da Composição dos Produtos 4Life
Dados da Composição dos Produtos 4LifeIlídio Gonçalves
 
Obama read my lips -obama fraudgate (serbian)
Obama   read my lips -obama fraudgate (serbian)Obama   read my lips -obama fraudgate (serbian)
Obama read my lips -obama fraudgate (serbian)VogelDenise
 
EL APRENDIZAJE COLABORATIVO A TRAVES DEL CURRICULUM “UNA ESTRATEGIA EFICAZ ...
EL APRENDIZAJE COLABORATIVO A TRAVES DEL CURRICULUM   “UNA ESTRATEGIA EFICAZ ...EL APRENDIZAJE COLABORATIVO A TRAVES DEL CURRICULUM   “UNA ESTRATEGIA EFICAZ ...
EL APRENDIZAJE COLABORATIVO A TRAVES DEL CURRICULUM “UNA ESTRATEGIA EFICAZ ...HER
 
Tragedy Genre project
Tragedy Genre projectTragedy Genre project
Tragedy Genre projectRithyu
 
Fler kunder i butiken
Fler kunder i butikenFler kunder i butiken
Fler kunder i butikenPeter Tilling
 
Webbshop ehandelsutb
Webbshop ehandelsutbWebbshop ehandelsutb
Webbshop ehandelsutbPeter Tilling
 
La mediación pedagógica en el proceso didáctico como proceso de comunicación
La mediación pedagógica en el proceso didáctico como proceso de comunicaciónLa mediación pedagógica en el proceso didáctico como proceso de comunicación
La mediación pedagógica en el proceso didáctico como proceso de comunicación1804power
 
Green Bonds in Brief
Green Bonds in BriefGreen Bonds in Brief
Green Bonds in BriefAs You Sow
 
Libro de Historia Tercero Medio
Libro de Historia Tercero MedioLibro de Historia Tercero Medio
Libro de Historia Tercero MedioSalvador Contreras
 

Destaque (20)

Lenguaje oral, primera tecnologia
Lenguaje oral, primera tecnologiaLenguaje oral, primera tecnologia
Lenguaje oral, primera tecnologia
 
Rwanda article
Rwanda articleRwanda article
Rwanda article
 
MI FAMILIA
MI FAMILIAMI FAMILIA
MI FAMILIA
 
Mapa de ruta directores. insc. inicial 2015
Mapa de ruta  directores. insc. inicial 2015Mapa de ruta  directores. insc. inicial 2015
Mapa de ruta directores. insc. inicial 2015
 
Etapas (para directores e inspectores inicial) de la inscripción condicional ...
Etapas (para directores e inspectores inicial) de la inscripción condicional ...Etapas (para directores e inspectores inicial) de la inscripción condicional ...
Etapas (para directores e inspectores inicial) de la inscripción condicional ...
 
Cc 5 14-13 - animals services snap adoption subsidy-presentation
Cc 5 14-13 - animals services snap adoption subsidy-presentationCc 5 14-13 - animals services snap adoption subsidy-presentation
Cc 5 14-13 - animals services snap adoption subsidy-presentation
 
Dados da Composição dos Produtos 4Life
Dados da Composição dos Produtos 4LifeDados da Composição dos Produtos 4Life
Dados da Composição dos Produtos 4Life
 
Lego
LegoLego
Lego
 
META IRAN
META IRANMETA IRAN
META IRAN
 
Obama read my lips -obama fraudgate (serbian)
Obama   read my lips -obama fraudgate (serbian)Obama   read my lips -obama fraudgate (serbian)
Obama read my lips -obama fraudgate (serbian)
 
EL APRENDIZAJE COLABORATIVO A TRAVES DEL CURRICULUM “UNA ESTRATEGIA EFICAZ ...
EL APRENDIZAJE COLABORATIVO A TRAVES DEL CURRICULUM   “UNA ESTRATEGIA EFICAZ ...EL APRENDIZAJE COLABORATIVO A TRAVES DEL CURRICULUM   “UNA ESTRATEGIA EFICAZ ...
EL APRENDIZAJE COLABORATIVO A TRAVES DEL CURRICULUM “UNA ESTRATEGIA EFICAZ ...
 
Tragedy Genre project
Tragedy Genre projectTragedy Genre project
Tragedy Genre project
 
Online social networking for the chemical sciences
Online social networking for the chemical sciencesOnline social networking for the chemical sciences
Online social networking for the chemical sciences
 
Fler kunder i butiken
Fler kunder i butikenFler kunder i butiken
Fler kunder i butiken
 
Webbshop ehandelsutb
Webbshop ehandelsutbWebbshop ehandelsutb
Webbshop ehandelsutb
 
La mediación pedagógica en el proceso didáctico como proceso de comunicación
La mediación pedagógica en el proceso didáctico como proceso de comunicaciónLa mediación pedagógica en el proceso didáctico como proceso de comunicación
La mediación pedagógica en el proceso didáctico como proceso de comunicación
 
Green Bonds in Brief
Green Bonds in BriefGreen Bonds in Brief
Green Bonds in Brief
 
Libro de Historia Tercero Medio
Libro de Historia Tercero MedioLibro de Historia Tercero Medio
Libro de Historia Tercero Medio
 
Evaluación experimentos en el aula
Evaluación experimentos en el aulaEvaluación experimentos en el aula
Evaluación experimentos en el aula
 
Obrigações
ObrigaçõesObrigações
Obrigações
 

Semelhante a Java Collection Framework: Core Interfaces, Implementations and Algorithms

Semelhante a Java Collection Framework: Core Interfaces, Implementations and Algorithms (20)

Collections
CollectionsCollections
Collections
 
JavaCollections.ppt
JavaCollections.pptJavaCollections.ppt
JavaCollections.ppt
 
JavaCollections.ppt
JavaCollections.pptJavaCollections.ppt
JavaCollections.ppt
 
Collections
CollectionsCollections
Collections
 
Collections
CollectionsCollections
Collections
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Collection
CollectionCollection
Collection
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Lists
ListsLists
Lists
 
collections
collectionscollections
collections
 
Java8
Java8Java8
Java8
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Java Collection
Java CollectionJava Collection
Java Collection
 

Mais de Gujarat Technological University (6)

Readme
ReadmeReadme
Readme
 
Ppt ppb module a
Ppt ppb   module aPpt ppb   module a
Ppt ppb module a
 
Object Oriented Programing and JAVA
Object Oriented Programing and JAVAObject Oriented Programing and JAVA
Object Oriented Programing and JAVA
 
XML - The Extensible Markup Language
XML - The Extensible Markup LanguageXML - The Extensible Markup Language
XML - The Extensible Markup Language
 
Data types ,variables,array
Data types ,variables,arrayData types ,variables,array
Data types ,variables,array
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 

Último

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 

Último (20)

INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 

Java Collection Framework: Core Interfaces, Implementations and Algorithms

  • 1. Topics • What is and Why Collections? • Core Collection Interfaces • Implementations • Algorithms • Custom Implementations • Interoperability TheAndroid-mania.com
  • 2. What is a Collection? • A “collection” object — sometimes called a container — is simply an object that groups multiple elements into a single unit. • Collections are used to store, retrieve, manipulate, and communicate aggregate data > Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers). TheAndroid-mania.com
  • 3. What is a Collection Framework? • A collections framework is a unified architecture for representing and manipulating collections • All collections frameworks contain the following: > Interfaces > Implementations > Algorithms TheAndroid-mania.com
  • 4. Benefits of Collection Framework • Reduces programming effort • Increases program speed and quality • Allows interoperability among unrelated APIs > The collection interfaces are the vernacular by which APIs pass collections back and forth • Reduce effort to learn and use new APIs • Reduces effort to design new APIs • Fosters software reuse > New data structures that conform to the standard collection interfaces are by nature reusable TheAndroid-mania.com
  • 6. Interfaces • Collection interfaces are abstract data types that represent collections > Collection interfaces are in the form of Java interfaces • Interfaces allow collections to be manipulated independently of the implementation details of their representation > Polymorphic behavior • In Java programming language (and other objectoriented languages), interfaces generally form a hierarchy > You choose one that meets your need as a type TheAndroid-mania.com
  • 7. Implementations • These are the concrete implementations of the collection interfaces. TheAndroid-mania.com
  • 8. Types of Implementations • General-purpose implementations • Special-purpose implementations • Concurrent implementations • Wrapper implementations • Convenience implementations • Abstract implementations TheAndroid-mania.com
  • 9. Implementations • Implementations are the data objects used to store collections, which implement the interfaces • Each of the general-purpose implementations (you will see in the following slide) provides all optional operations contained in its interface • Java Collections Framework also provides several special-purpose implementations for situations that require nonstandard performance, usage restrictions, or other unusual behavior TheAndroid-mania.com
  • 10. General Purpose Implementations interfaces Implementations Hash Table Resizable Array Tree Linked List HashTbale + Linked List Set Hash Set Tree Set Linked Hash Set List Array List Linked List Queue Map Hash Map Tree Map Linked Hash Map TheAndroid-mania.com
  • 11. Algorithms • These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces • The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface > In essence, algorithms are reusable functionality. TheAndroid-mania.com
  • 13. Core Collection Interfaces Hierarchy Collection Set List Queue Sorted Set Map Sorted Map TheAndroid-mania.com
  • 14. Core Collection Interfaces • Core collection interfaces are the foundation of the Java Collections Framework • Core collection interfaces form a inheritance hierarchy among themselves > You can create a new Collection interface from them (highly likely you don't have to) TheAndroid-mania.com
  • 16. “Collection” Interface • The root of the collection hierarchy • Is the least common denominator that all collection implement > Every collection object is a type of Collection interface • Is used to pass collection objects around and to manipulate them when maximum generality is desired > Use Collection interface as a type • JDK doesn't provide any direct implementations of this interface but provides implementations of more specific sub interfaces, such as Set and List. TheAndroid-mania.com
  • 17. “Collection” Interface (Java SE 5) public interface Collection<E> extends Iterable<E> { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); TheAndroid-mania.com
  • 18. Example  import java.util.*;  import java.util.Collection;  public class collectioninterface {  public static void main(String[] args) {  Collection collection = new ArrayList();  collection.add("Dev");  collection.add("Manuals");  System.out.print(" Elements Of the Array List are ");  System.out.print(collection + ".");  }  } TheAndroid-mania.com
  • 19. add() and remove() methods of Collection Interface • The add() method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't • It guarantees that the Collection will contain the specified element after the call completes, and returns true if the Collection changes as a result of the call. > add() method of Set interface follows “no duplicate” rule TheAndroid-mania.com
  • 21. Two Schemes of Traversing Collections • for-each > The for-each construct allows you to concisely traverse a collection or array using a for loop for (Object o: collection) System.out.println(o); • Iterator > An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired TheAndroid-mania.com
  • 22. Iterator Iterator means an Object with which we can travel all through a range of elements. It works like a Pointer. In database, Sometimes Iterator is called a Cursor. Class signature : Public interface Iterator Enumeration interface is replaced by iterator in collections frame work.the advantages over Enumerations: Iterator allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method name have been improved. We can print from any index number , but need not all the elements. TheAndroid-mania.com
  • 23. Iterator Interface public interface Iterator { boolean hasNext(); Object next(); void remove(); //optional } • hasNext() method returns true if the iteration has more elements • next() method returns the next element in the iteration • remove() is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress TheAndroid-mania.com
  • 24. Use Iterator over for-each when you need to • Remove the current element > The for-each construct hides the iterator, so you cannot call remove > Therefore, the for-each construct is not usable for filtering. static void filter(Collection<?> c) { for (Iterator<?> it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); } • Iterate over multiple collections in parallel TheAndroid-mania.com
  • 25. List Iterator Interface List iterator is an interface that contains methods to retrieve the elements from a collection object, both in forward and reverse directions. It has following methods: boolean hasNext(); returns true if the List Iterator has more elements when traversing the list in the forward direction. boolean hasPrevious(); returns true if the List Iterator has more elements when traversing the list in the reverse direction. element next(); returns the next element. element previous(); returns the previous element in the list. void remove(); removes from the list the last element that was returned. TheAndroid-mania.com
  • 27. “List” Interface • An ordered collection (sometimes called a sequence) • Lists can contain duplicate elements • The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position) > If you've used Vector, you're already familiar with the general basics of List TheAndroid-mania.com
  • 28. Additional Operations Supported by “List” Interface over “Collection” • Positional access — manipulates elements based on their numerical position in the list • Search — searches for a specified object in the list and returns its numerical position • Iteration — extends Iterator semantics to take advantage of the list's sequential nature • Range-view — performs arbitrary range operations on the list. TheAndroid-mania.com
  • 29. “List” Interface public interface List<E> extends Collection<E> { // Positional access E get(int index); E set(int index, E element); //optional boolean add(E element); //optional void add(int index, E element); //optional E remove(int index); //optional boolean addAll(int index, Collection<? extends E> c); //optional // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator<E> listIterator(); ListIterator<E> listIterator(int index); // Range-view TheAndroid-mania.com
  • 30. Implementations of “List” Interface • ArrayList > Offers constant-time positional access > Fast > Think of ArrayList as Vector without the synchronization overhead > Most commonly used implementation • LinkedList > Use it you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior TheAndroid-mania.com
  • 31. “Array List” ArrayList is a Sub class of AbstractList and implements List. Signature: Array List includes a feature called Dynamic Arrays-memory is dynamically allotted and re-allotted to accommodate all the elements. Array list is not Synchronised. public class ArrayList extends AbstractList implements List, Cloneable,Serializable TheAndroid-mania.com
  • 32. Array List Examples import java.util.*; public class IteratorArrayList{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add(new Integer(10)); al.add(new Double(25.5)); al.add(new Boolean(false)); al.add(new String("santhosh")); al.add(new StringBuffer("Trainer")); al.add(new Date()); Iterator it=al.iterator(); while(it.hasNext()){ Object obj=it.next(); System.out.println(obj); if(obj instanceof Number) { it.remove(); } } TheAndroid-mania.com
  • 33. Linked List A linked List contains a group of elements in the form of nodes. Each node will have 3 fields Data Field contains data And the two Link fields contain references to previous and next nodes. Linked List is very convenient to store data. Inserting the elements into the linked list and removing the elements from the linked list is done quickly and takes the same amount of time. TheAndroid-mania.com
  • 35. “Set” Interface • A collection that cannot contain duplicate elements • Models the mathematical set abstraction and is used to represent sets > cards comprising a poker hand > courses making up a student's schedule > the processes running on a machine • The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. TheAndroid-mania.com
  • 36. “Set” Interface (Java SE 5) public interface Set<E> extends Collection<E> { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional // Array Operations Object[] toArray(); TheAndroid-mania.com
  • 37. “Sorted Set” Interface • A Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering • Sorted sets are used for naturally ordered sets, such as word lists and membership roll. TheAndroid-mania.com
  • 38. Implementations of “Set” Interface Implementations of “Set” Interface • HashSet • TreeSet • LinkedHashSet TheAndroid-mania.com
  • 39. HashSet • HashSet is much faster than TreeSet (constant time versus log-time for most operations) but offers no ordering guarantees • Mostly commonly used implementation. Caveats of Using HashSet • Iteration is linear in the sum of the number of entries and the number of buckets (the capacity). > Choosing an initial capacity that's too high can waste both space and time. > Choosing an initial capacity that's too low wastes time by copying the data structure each time it's forced to increase its capacity. TheAndroid-mania.com
  • 40. Example for HashSet import java.util.*; public class HashSetinfo{ public static void main(String args[]){ HashSet hs=new HashSet(); Integer il=new Integer(10); hs.add(il); Double d1=new Double(10.5); hs.add(d1); hs.add(new Integer(20)); hs.add("Santhosh Teleman"); hs.add(new String("Trainer")); System.out.println("Number of elements"+hs.size()); System.out.println("il exists:"+hs.contails(il)); System.out.println("Elements before remeoval"); System.out.println(hs); hs.remove(d1); System.out.println("elements after remeoval"); System.out.println(hs); TheAndroid-mania.com
  • 41. TreeSet • When you need to use the operations in the SortedSet interface, or if value-ordered iteration is required. This class guarantees that the sorted set will be in ascending element order,sorted according to to the natural order of the elements. To optimize TreeSet and HashSet space usage, we can start with less initial capacity and load capacity. Class Signature: public class TreeSet extends AbstractSet implements SortedSet ,Cloneable, Serializable TheAndroid-mania.com
  • 42. Example: Set Interface & TreeSet Import java.util.*; Public Class TreeSet{ public static void main(String[] args) { Set ts = new TreeSet(); ts.add("one"); ts.add("two"); ts.add("three"); ts.add("four"); ts.add("three"); System.out.println("Members from TreeSet = " + ts); } Result: Members from TreeSet = [four, one, three, two] TheAndroid-mania.com
  • 43. LinkedHashSet • Implemented as a hash table with a linked list running through it • Provides insertion-ordered iteration (least recently inserted to most recently) and runs nearly as fast as HashSet. • Spares its clients from the unspecified, generally chaotic ordering provided by HashSet without incurring the increased cost associated with TreeSet. TheAndroid-mania.com
  • 44. Example: Set Interface & LinkedHashSet Import java.util.*; public class LinkedHashSet{ public static void main(String[] args) { Set ts2 = new LinkedHashSet(); ts2.add(2); ts2.add(1); ts2.add(3); ts2.add(3); System.out.println("Members from LinkedHashSet = " + ts2); } } Result: Members from LinkedHashSet = [2, 1, 3] TheAndroid-mania.com
  • 45. Example: Set Interface & HashSet public class Main { public static void main(String[] args) { Set s = new HashSet(); // Order is not guaranteed MyOwnUtilityClass.checkDuplicate(s, args); s = new TreeSet(); // Order according to values MyOwnUtilityClass.checkDuplicate(s, args); s = new LinkedHashSet(); // Order according to insertion MyOwnUtilityClass.checkDuplicate(s, args); } } TheAndroid-mania.com
  • 46. Example: Set Interface & HashSet The numbers are added in the following order 2 3 4 1 2 Set type = java.util.HashSet [3, 2, 4, 1] Set type = java.util.TreeSet [1, 2, 3, 4] Set type = java.util.LinkedHashSet [2, 3, 4, 1] TheAndroid-mania.com
  • 48. “Map” Interface • Handles key/value pairs. • A Map cannot contain duplicate keys; each key can map to at most one value. If you've used Hash table, you're already familiar with the basics of Map. Class Signature: public interface map TheAndroid-mania.com
  • 49. “Map” Interface (Java SE 5) public interface Map<K,V> { // Basic operations V put(K key, V value); V get(Object key); V remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk operations void putAll(Map<? extends K, ? extends V> m); void clear(); // Collection Views public Set<K> keySet(); public Collection<V> values(); public Set<Map.Entry<K,V>> entrySet(); // Interface for entrySet elements public interface Entry { TheAndroid-mania.com
  • 50. “Sorted Map” Interface • A Map that maintains its mappings in ascending key order > This is the Map analog of Sorted Set. • Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories. TheAndroid-mania.com
  • 51. Implementations of “Map” Interface • Hash Map > Use it you want maximum speed and don't care about iteration order. > Most commonly used implementation • Tree Map > Use it when you need Sorted Map operations or key-ordered Collection-view iteration • Linked HashMap > Use if you want near-Hash Map performance and insertion order iteration TheAndroid-mania.com
  • 52. Hash Map HashMap is like Hashtable which stores key/value pairs. It implements map interface and we can use all the operations (methods) of map interface. It permits null values and the null key. Hash map is almost equivalent to HashTable, except that it is un- synchronised and permits nulls. Order of elements is not guaranteed. Class signature: public class Hashmap extends AbstractMap implements Map,Cloneable,Serializable TheAndroid-mania.com
  • 53. Tree map This class extends AbstractMap and implements SortedMap. This class Guarantees that the elements will be in ascending key order, sorted according to the natural order based on the keys. Class signature: public class Treemap extends AbstractMap implements SortedMap , Cloneable, Serializable TheAndroid-mania.com
  • 55. “Queue” Interface • A collection used to hold multiple elements prior to processing • Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations • Typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. TheAndroid-mania.com
  • 56. Implementations of Queue Interface • General purpose Queue implementations > LinkedList implements the Queue interface, providing FIFO queue operations for add, poll, and so on > PriorityQueue class is a priority queue based on the heap data structure > This queue orders elements according to an order specified at construction time, which can be the elements' natural ordering or the ordering imposed by an explicit Comparator. • Concurrent Queue implementations TheAndroid-mania.com
  • 58. Collections Class • Provides methods to return the empty Set, List, and Map — emptySet, emptyList, and emptyMap. > The main use of these constants is as input to methods that take a Collection of values when you don't want to provide any values at all > tourist.declarePurchases(Collections.emptySet()); • Provides methods for sorting and shuffling > Collections.sort(l); > Collections.shuffle(l); TheAndroid-mania.com
  • 60. Abstract Classes • Includes abstract implementations > AbstractCollection > AbstractSet > AbstractList > AbstractSequentialList > AbstractMap • To aid in custom implementations > Reduces code you have to write TheAndroid-mania.com
  • 62. Algorithms • Sorting • Shuffling • Routine data manipulation • Searching • Composition • Find extreme values TheAndroid-mania.com
  • 63. Algorithms • Provided as static methods of Collections class • The first argument is the collection on which the operation is to be performed • The majority of the algorithms provided by the Java platform operate on List instances, but a few of them operate on arbitrary Collection instances TheAndroid-mania.com
  • 64. Sorting • The sort algorithm reorders a List so that its elements are in ascending order according to an ordering relationship • Two forms of the operations > takes a List and sorts it according to its elements' natural ordering > takes a Comparator in addition to a List and sorts the elements with the Comparator TheAndroid-mania.com
  • 65. Natural Ordering • The type of the elements in a List already implements Comparable interface • Examples > If the List consists of String elements, it will be sorted into alphabetical order > If it consists of Date elements, it will be sorted into chronological order > String and Date both implement the Comparable interface. Comparable implementations provide a natural ordering for a class, which allows objects of that class to be sorted automatically • If you try to sort a list, the elements of which do not implement Comparable, Collections.sort(list) will throw a ClassCastException. TheAndroid-mania.com
  • 66. Sorting by Natural Order of List // Set up test data String n[] = { new String("John"), new String("Karl"), new String("Groucho"), new String("Oscar") }; // Create a List from an array List l = Arrays.asList(n); // Perform the sorting operation Collections.sort(l); TheAndroid-mania.com
  • 67. Sorting by Comparator Interface • A comparison function, which imposes a total ordering on some collection of objects • Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order • Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural Ordering. TheAndroid-mania.com
  • 68. Sorting by Natural Order of List // Set up test data ArrayList u2 = new ArrayList(); u2.add("Beautiful Day"); u2.add("Stuck In A Moment You Can't Get Out Of"); u2.add("Elevation"); u2.add("Walk On"); u2.add("Kite"); u2.add("In A Little While"); u2.add("Wild Honey"); u2.add("Peace On Earth"); u2.add("When I Look At The World"); u2.add("New York"); u2.add("Grace"); Comparator comp = Comparators.stringComparator(); Collections.sort(u2, comp); TheAndroid-mania.com
  • 69. Shuffling • The shuffle algorithm does the opposite of what sort does, destroying any trace of order that may have been present in a List > That is, this algorithm reorders the List based on input from a source of randomness such that all possible permutations occur with equal likelihood, assuming a fair source of randomness • Useful in implementing games of chance > could be used to shuffle a List of Card objects representing a deck > generating test cases TheAndroid-mania.com
  • 70. Routine Data Manipulation • The Collections class provides five algorithms for doing routine data manipulation on List objects > reverse — reverses the order of the elements in a List. > fill — overwrites every element in a List with the specified value. This operation is useful for reinitializing a List. > copy — takes two arguments, a destination List and a source List, and copies the elements of the source into the destination, overwriting its contents. The destination List must be at least as long as the source. If it is longer, the remaining elements in the destination List are unaffected. > swap — swaps the elements at the specified positions in a List. > addAll — adds all the specified elements to a Collection. The elements to be added may be specified individually or as an array. TheAndroid-mania.com
  • 71. Searching • The Collections class has binarySearch() method for searching a specified element in a sorted List // Set up testing data String name[] = { new String("Sang"), new String("Shin"), new String("Boston"), new String("Passion"), new String("Shin"), }; List l = Arrays.asList(name); int position = Collections.binarySearch(l, "Boston"); System.out.println("Position of the searched item = " + position); TheAndroid-mania.com
  • 72. Composition • Collections.frequency(l) — counts the number of times the specified element occurs in the specified collection • Collections.disjoint(l1, l2) — determines whether two Collections are disjoint; that is, whether they contain no elements in common. The Collections class has binarySearch() method for searching a specified element in a sorted List. TheAndroid-mania.com

Notas do Editor

  1. 5/15/2013 TheAndroid-mania.com