Java 2 Collections Framework - PowerPoint PPT Presentation

About This Presentation
Title:

Java 2 Collections Framework

Description:

Title: Java 2 Collections Framework Author: Leonardo Cole Neto Last modified by: Leonardo Cole Neto Created Date: 7/10/2003 11:59:42 AM Document presentation format – PowerPoint PPT presentation

Number of Views:214
Avg rating:3.0/5.0
Slides: 26
Provided by: Leonardo84
Category:

less

Transcript and Presenter's Notes

Title: Java 2 Collections Framework


1
Java 2 Collections Framework
  • Leonardo Cole Neto

2
Roteiro
  • Introdução
  • Interfaces
  • Implementações
  • Algoritmos
  • Customizando Implementações
  • Resolvendo Problemas Comuns

3
Introdução
  • O que é uma coleção?
  • Um objeto que agrupa múltiplos elementos em uma
    única unidade
  • Usadas para armazenar, recuperar e manipular
    elementos que formam um grupo natural.
  • Ex. Vector, Hashtable, array (JDK 1.1)

4
Collections Framework
  • Conjunto de interfaces, implementações e
    algoritmos
  • Vantagens
  • Reduz esforço de programação
  • Aumenta velocidade e qualidade na programação
  • Permite interoperabilidade entre APIs
  • Reduz esforço para aprender uma nova API
  • Reduz esforço para criar uma nova API
  • Promove reuso

5
Interfaces
6
Interfaces
  • São utilizadas sempre que possível
  • Parâmetros de métodos
  • Retorno dos métodos
  • Permite polimorfismo
  • Existem operações opcionais
  • UnsupportedOperationException

7
Collection
  • Raiz da hierarquia
  • Grupo mais genérico de elementos
  • Não garante nas implementações
  • Duplicatas
  • Ordenação
  • Não possui nenhuma implementação direta
  • Iterator, extrutura de navegação
  • next, hasNext, remove(optional)

8
Collection
  • public interface Collection
  • // Basic Operations
  • int size()
  • boolean isEmpty()
  • boolean contains(Object element)
  • boolean add(Object element) // Optional
  • boolean remove(Object element) // Optional
  • Iterator iterator()
  • // Bulk Operations
  • boolean containsAll(Collection c)
  • boolean addAll(Collection c) // Optional
  • boolean removeAll(Collection c) // Optional
  • boolean retainAll(Collection c) // Optional
  • void clear() // Optional
  • // Array Operations
  • Object toArray()
  • Object toArray(Object a)

9
Set
  • Extends Collection
  • Não contém duplicatas
  • Não garante ordem entre os elementos
  • Não acrescenta métodos
  • Caracterização de tipo
  • Operações
  • Subconjunto (containsAll)
  • União (addAll)
  • Intercessão (reatinaAll)
  • Diferença (removeAll)

10
List
  • Extends Collection
  • Coleção ordenada (Sequência)
  • Pode ter duplicatas
  • Controle na posição de inserção ou remoção
  • Acesso aos elementos pelo índice
  • ListIterator
  • hasPrevious,previous, nextIndex, previousIndex

11
List
  • public interface List extends Collection
  • // Positional Access
  • Object get(int index)
  • Object set(int index, Object element)
    // Optional
  • void add(int index, Object element)
    // Optional
  • Object remove(int index)
    // Optional
  • abstract boolean addAll(int index, Collection
    c) // Optional
  • // Search
  • int indexOf(Object o)
  • int lastIndexOf(Object o)
  • // Iteration
  • ListIterator listIterator()
  • ListIterator listIterator(int index)
  • // Range-view
  • List subList(int from, int to)

12
Map
  • Mapeamento de chaves em valores
  • Não possui chaves duplicadas
  • Cada chave leva a somente um elemento
  • Para uma busca efetiva, o objeto da chave deve
    reimplementar os métodos
  • hashCode
  • equals

13
Map
  • public interface Map
  • // Basic Operations
  • Object put(Object key, Object value)
  • Object get(Object key)
  • Object remove(Object key)
  • boolean containsKey(Object key)
  • boolean containsValue(Object value)
  • int size()
  • boolean isEmpty()
  • // Bulk Operations
  • void putAll(Map t)
  • void clear()
  • // Collection Views
  • public Set keySet()
  • public Collection values()
  • public Set entrySet()

14
Ordenação de Objetos
  • java.lang.Comparable
  • Ordem natural
  • compareTo(object)
  • java.util.Comparator
  • Provê multiplas formas de ordenação
  • compare(object,object)
  • Retornos
  • Inteiro negativo menor que
  • Zero iguais
  • Inteiro positivo maior que
  • Não são elementos do framework, apenas estruturas
    complementares

15
Ordenação de Objetos
Class Natural Ordering
Byte signed numerical
Character unsigned numerical
Long signed numerical
Integer signed numerical
Short signed numerical
Double signed numerical
Float signed numerical
BigInteger signed numerical
BigDecimal signed numerical
File system-dependent lexicographic on pathname.
String lexicographic
Date chronological
CollationKey locale-specific lexicographic
16
SortedSet
  • Extends Set
  • Elementos ordenados de forma ascendente
  • Algumas operações a mais para aproveitar a
    vantagem da ordenação
  • public interface SortedSet extends Set
  • // Range-view
  • SortedSet subSet(Object fromElement, Object
    toElement)
  • SortedSet headSet(Object toElement)
  • SortedSet tailSet(Object fromElement)
  • // Endpoints
  • Object first()
  • Object last()
  • // Comparator access
  • Comparator comparator()

17
SortedMap
  • Extends Map
  • Mapeamento onde as chaves são ordenadas de forma
    ascendente.
  • public interface SortedMap extends Map
  • Comparator comparator()
  • SortedMap subMap(Object fromKey, Object
    toKey)
  • SortedMap headMap(Object toKey)
  • SortedMap tailMap(Object fromKey)
  • Object firstKey()
  • Object lastKey()

18
Implementações
                                Implementations Implementations Implementations Implementations
                                Hash Table Resizable Array Balanced Tree Linked List
Interfaces Set HashSet   TreeSet  
Interfaces List   ArrayList, Vector   LinkedList
Interfaces Map HashMap, Hashtable   TreeMap  
  • Hashtable x HashMap
  • LinkedList x ArrayList x Vector
  • TreeSet implements SortedSet
  • TreeMap implements SortedMap

19
Wrapper implementations
  • Collections decorator
  • //Synchronization
  • public static Collection synchronizedCollection(Co
    llection c)
  • public static Set synchronizedSet(Set s)
  • public static List synchronizedList(List list)
  • public static Map synchronizedMap(Map m)
  • public static SortedSet synchronizedSortedSet(Sort
    edSet s)
  • public static SortedMap synchronizedSortedMap(Sort
    edMap m)
  • //Unmodifiable
  • public static Collection unmodifiableCollection(Co
    llection c)
  • public static Set unmodifiableSet(Set s)
  • public static List unmodifiableList(List list)
  • public static Map unmodifiableMap(Map m)
  • public static SortedSet unmodifiableSortedSet(Sort
    edSet s)
  • public static SortedMap unmodifiableSortedMap(Sort
    edMap m)

20
Convenience Implementations
  • Arrays
  • asList
  • binarySearch
  • Collections
  • nCopies (immutable)
  • singleton (immutable)

21
Algoritmos
  • Sorting
  • Collections.sort(list)
  • Arrays.sort(array)
  • Optimized merge sort (log n)
  • Shuffling
  • Collections.shuffle(list)
  • Routine Data Manipulation
  • Collections.reverse(list)
  • Collections.fill(list,value)
  • Collections.copy(detination,source)
  • Arrays.fill(array,value)
  • System.arrayCopy(dest,destPos,src,srcPos,length)

22
Algoritmos
  • Searching
  • Collections.binarySearch(list,value)
  • Arrays.binarySearch(array,value)
  • Finding Extreme Values
  • Collections.max(list)
  • Collections.min(list)

23
Customizando Implementações
  • Possíveis objetivos
  • Persistência, Aplicação específica, Concorrência,
    Performance, Funcionalidade, Conveniência,
    Adaptação
  • AbstractCollection (bag)
  • iterator, size
  • AbstractSet
  • iterator, size
  • AbstractList (uses array)
  • Positional methods
  • AbstractSequencialList (uses linked list)
  • listIterator, iterator
  • AbstractMap
  • EntrySet view, put

24
Resolvendo Problemas Comuns
  • Refer to
  • http//java.sun.com/docs/books/tutorial/collection
    s/problems/index.html

25
Referências
  • Joshua Bloch, The Java Tutorial, Collections
    Framework, available at http//java.sun.com/docs/b
    ooks/tutorial/collections/
Write a Comment
User Comments (0)
About PowerShow.com