MELJUN CORTES Java collections

34
The Collections The Collections Framework Framework Java Data Structures Java Data Structures MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCS MBA,MPA,BSCS

Transcript of MELJUN CORTES Java collections

The Collections The Collections FrameworkFramework

Java Data StructuresJava Data Structures

MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS

What You Should LearnWhat You Should Learn

DefinitionDefinition Types of CollectionsTypes of Collections Using CollectionsUsing Collections

IteratingIterating CopyingCopying Collections in Java 1.5Collections in Java 1.5

DefinitionDefinition

CollectionCollection object that groups multiple elements into object that groups multiple elements into

a single unit a single unit an array is a collectionan array is a collection

DefinitionDefinition

Collections FrameworkCollections Framework unified architecture for representing and unified architecture for representing and

manipulating collections manipulating collections

DefinitionDefinition

Collections FrameworkCollections Framework Three Elements:Three Elements:

InterfacesInterfaces how you handle the collection

ImplementationsImplementations the classes that actually hold the data

AlgorithmsAlgorithms useful routines

The Java Collections The Java Collections FrameworkFramework

InterfacesInterfaces

Collection

List Set Queue Map

The Java Collections The Java Collections FrameworkFramework Collection Collection

super type of List, Set and Queuesuper type of List, Set and Queue ListList

stores elements in the order they were added, similar stores elements in the order they were added, similar to an array only growableto an array only growable

Set Set stores only unique elements, no duplicatesstores only unique elements, no duplicates

QueueQueue stores elements in preparation for processing, usually stores elements in preparation for processing, usually

either by FIFO or by priorityeither by FIFO or by priority Map Map

stores key-value pairs, like for a lookup tablestores key-value pairs, like for a lookup table

CollectionCollection

Defines common Defines common methodsmethods addadd addAlladdAll removeremove removeAllremoveAll clearclear

containscontains containsAllcontainsAll isEmptyisEmpty sizesize toArraytoArray iteratoriterator

ListsLists

““growable array”growable array” Elements ordered in the sequence they Elements ordered in the sequence they

were added.were added. Allows you to get and set using and indexAllows you to get and set using and index

myList.set(4, “Barracuda”);

String fish = myList.get(4);

ListsLists

Implementations:Implementations: ArrayListArrayList LinkedListLinkedList VectorVector

ListsLists

ArrayListArrayList backed by an Object arraybacked by an Object array fast in getting and setting elementsfast in getting and setting elements slow in inserting and removingslow in inserting and removing

ListsListsLinkedListLinkedList slow in getting and setting elementsslow in getting and setting elements fast in inserting and removingfast in inserting and removing

ListsLists

VectorVector Just like an ArrayList only all methods are Just like an ArrayList only all methods are

synchronized.synchronized. Was the only list available prior to Java Was the only list available prior to Java

1.1.1.1. ArrayList is preferred to Vector because ArrayList is preferred to Vector because

programmer has control over programmer has control over synchronization.synchronization.

SetsSets

No duplicatesNo duplicates Maintains its Maintains its ownown order order Same interface as CollectionSame interface as Collection

SetsSets

Implementations:Implementations: HashSetHashSet TreeSetTreeSet

SetsSets

HashSetHashSet Stores data in a hash Stores data in a hash

table implementation.table implementation. Not sorted “naturally”.Not sorted “naturally”.

SetsSets TreeSetTreeSet

Stores data in a binary Stores data in a binary tree to search for tree to search for duplicates.duplicates.

Sorted “naturally”Sorted “naturally” Implements SortedSet Implements SortedSet

interfaceinterface

QueuesQueues

For holding elements prior to processing.For holding elements prior to processing. Typically FIFO but may be ordered by Typically FIFO but may be ordered by

prioritypriority Implementations:Implementations:

LinkedList (FIFO)LinkedList (FIFO) PriorityQueuePriorityQueue

QueuesQueues

MethodsMethods elementelement offeroffer PeekPeek pollpoll removeremove

MapsMaps

An object that maps keys to valuesAn object that maps keys to values Keys are uniqueKeys are unique

Key (User ID – String)Key (User ID – String) Value (some object)Value (some object)

““C234D7”C234D7”

““A497X3”A497X3”

““B252M5”B252M5”

““R567B7”R567B7”

MapsMaps

Using a map:Using a map:

myMap.put(“T234Y9”, someObject);

Getting from a map:Getting from a map:

myMap.get(“T234Y9”);

MapsMaps

Implementations:Implementations: HashMapHashMap TreeMapTreeMap HashTableHashTable

MapsMaps

HashMapHashMap Keys are ordered using a hash table Keys are ordered using a hash table

implementation, similar to HashSet.implementation, similar to HashSet. Keys are not sorted “naturally”. Keys are not sorted “naturally”.

MapsMaps

TreeMapTreeMap Uses a binary tree to order keys.Uses a binary tree to order keys. Keys are sorted “naturally”.Keys are sorted “naturally”.

MapsMaps

HashTableHashTable Just like an HashMap only all methods are Just like an HashMap only all methods are

synchronized.synchronized. Was the only map available prior to Java 1.1.Was the only map available prior to Java 1.1. HashMap is preferred to HashTable because HashMap is preferred to HashTable because

programmer has control over synchronization.programmer has control over synchronization.

MapsMaps

HashMap vs. TreeMapHashMap vs. TreeMap HashMap is usually faster than TreeMap.HashMap is usually faster than TreeMap. Use TreeMap if you need keys to be sorted.Use TreeMap if you need keys to be sorted.

IteratorIterator

Prior to Java 1.5, Iterator was used to Prior to Java 1.5, Iterator was used to provide generic iteration for Collection provide generic iteration for Collection implementations.implementations.

IteratorIterator

//example: collection of strings

Iterator iter = collection.iterator();

while(iter.hasNext) {

String s = (String) iter.next();

// do stuff with s

}

AlgorithmsAlgorithms

java.util.Collectionsjava.util.Collections Utility class where useful routines can be Utility class where useful routines can be

found.found. Sorting Searching Finding Maximum, Minimum Reversing Shuffling more...

Java 1.5 EnhancementsJava 1.5 Enhancements

GenericsGenerics For-Each LoopFor-Each Loop AutoboxingAutoboxing

GenericsGenerics

You can enforce type on the collection.You can enforce type on the collection.

List<String> list = new ArrayList<String>();

String s = list.get(5); // no need to cast!

list.add(new Integer(5)); XXX // will not compile

For-Each LoopFor-Each Loop

Use the same loop construct for arrays Use the same loop construct for arrays and collections:and collections:

for(String s : collection) {

System.out.println(s);

}

AutoboxingAutoboxing

You can now use primitives in CollectionsYou can now use primitives in Collections

list.add(3);

map.put(4857, employee);

Best PracticesBest Practices

Always use the Interface.Always use the Interface. Always use the Iterator (1.4) or the For-Always use the Iterator (1.4) or the For-

Each Loop (1.5).Each Loop (1.5).