Collections&Generics

25 %
75 %
Information about Collections&Generics
Technology

Published on April 7, 2009

Author: hortis

Source: slideshare.net

Description

Presentation du chapttre 7 de la certification Java, donnée les 28 mars et 2 avril 2009

Collections & Generics, une introduction Par Didier Besset didier.besset@hortis.ch Hortis GRC SA - www.hortis.ch

Collection interface Iterable<T> iterator() Collection <T> add(T) addAll(Collection<T>) remove(T) Iterator<T> removeAll (Collection<T>) hasNext() retainAll (Collection<T>) next() clear() remove() contains(T) containsAll(Collection<T>) isEmpty() size() toArray() iterator() 2 Hortis GRC SA - www.hortis.ch Collections & Generics

Utilisation d’un Iterable  Seule façon d’accéder au contenu d’une collection quelconque:  for( final T item: collection) {  ... faire quelque chose... } 3 Hortis GRC SA - www.hortis.ch Collections & Generics

Utilisation d’un Iterator  Seule façon d’accéder et de modifier le contenu d’une collection quelconque: final Iterator<T> iter = collection.iterator(); while(iter.hasNext()) { final T item = iter.next(); ... faire quelque chose... if (... condition...) { iter.remove(); } } 4 Hortis GRC SA - www.hortis.ch Collections & Generics

Utilisation d’un Iterator dans un “for”  Le contenu reste identique: for(final Iterator<T> iter = collection.iterator(); iter.hasNext();) { final T item = iter.next(); ... faire quelque chose... if (... condition...) { iter.remove(); } } 5 Hortis GRC SA - www.hortis.ch Collections & Generics

Comparable  Donne un ordre “naturel”: Interface Comparable<T> { int compareTo(T o); }  Exemple pour une liste: final List<T extends Comparable<T>> myList = ... Collections.sort(myList); 6 Hortis GRC SA - www.hortis.ch Collections & Generics

Comparator  Pour mettre de l’ordre dans les collections: Interface Comparator<T> { int compare(T o1, To2); }  Exemple pour une liste: final List<T> myList = ... final Comparator<T> myComparator = ... Collections.sort(myList, myComparator); 7 Hortis GRC SA - www.hortis.ch Collections & Generics

Lists and Sets  Une liste possède un ordre,  Un Set ne contient aucun doublon. 8 Hortis GRC SA - www.hortis.ch Collections & Generics

Lists and Sets Collection<T> List<T> Set<T> get(int) remove(int) SortedSet<T> add(int,T) comparator() set(int,T) first() indexOf(T) last() lastIndexOf(T) subSet(T,T) subList(int,int) headSet(T) tailSet(T) 9 Hortis GRC SA - www.hortis.ch Collections & Generics

Maps  Permet un accès indexé par n’importe quel object:  “buckets” adressés par le hashCode,  Séparation à l’intérieur d’un “bucket” à l’aide de la méthode equals . 10 Hortis GRC SA - www.hortis.ch Collections & Generics

Maps Map<K,T> put(K,T) putAll(Map<K,T>) remove(K) get(K) clear() size() containsKey(K) SortedMap<K,T> containsValue(T) comparator() keySet() firstKey() values() lastKey() subMap(K,K) headMap(K) Collection<T> tailMap(K) Set<K> 11 Hortis GRC SA - www.hortis.ch Collections & Generics

Synchronization Collection type Synchronized object factory Collection synchronizedCollection() List synchronizedList() Set synchronizedSet() SortedSet synchronizedSortedSet() Map synchronizedMap() SortedMap synchronizedSortedMap() 12 Hortis GRC SA - www.hortis.ch Collections & Generics

Full collection hierachy Collection AbstractCollection List Set AbstractList AbstractSet AbstractQueue SortedSet ArrayList Vector HashSet TreeSet AbstractSequentialList Stack LinkedList 13 Hortis GRC SA - www.hortis.ch Collections & Generics

Full Map hierachy Dictionary Map AbstractMap Hashtable SortedMap HashMap TreeMap WeakHashMap 14 Hortis GRC SA - www.hortis.ch Collections & Generics

Boxing and auto-boxing  Une Collection ou une Map contient des objects, pas des primitives,  Usage correct (boxing explicite) : Collection<Integer> measures = ...; measures.add(new Integer(4));  Usage permis (boxing implicite) : measures.add(4); 15 Hortis GRC SA - www.hortis.ch Collections & Generics

Convertions  Arrays → Listes : MyClass[] myArray = ...; Collection<MyClass> measures = Arrays.asList(myArray); Listes → Arrays : Collection<MyClass> measures = ...; MyClass[] myArray = measures.toArray( new MyClass[measures.size()]); 16 Hortis GRC SA - www.hortis.ch Collections & Generics

“Backed” collections  Une “feature” dangereuse des collections construites sur des Map: keySet() tailset() values() tailmap() headset() subSet() headmap() subMap() 17 Hortis GRC SA - www.hortis.ch Collections & Generics

keySet() tailset() values() tailmap() headset() subSet() headmap() subMap() 18 Hortis GRC SA - www.hortis.ch Collections & Generics

Déclarations générique  Déclaration pour le compilateur seulement,  Le type “générique” n’a pas d’existence dans la machine virtuelle,  Un type se déclare au niveau:  de la classe,  d’une méthode (non-static ou static);  Il s’agit donc d’un simple “pattern-matching” 19 Hortis GRC SA - www.hortis.ch Collections & Generics

Différences fondamentale  Les arrays ont accès à l’héritage: Number[] measures = new Integer[4];  Les collections pas! List<Number> measures = new ArrayList<Integer>();  ... parce que le type de la déclaration de la collection n’existe pas en dehors du compilateur. 20 Hortis GRC SA - www.hortis.ch Collections & Generics

Comment faire?  On utilise la notation <? extends xxx>,  Par exemple : List<? extends Number> measures = new ArrayList<Integer>();  Par contre : Number meter = measures.get(0); Integer mm = (Integer) measures.get(1); 21 Hortis GRC SA - www.hortis.ch Collections & Generics

Exemple: filtre générique public abstract class AbstractObjectFilter<T> { private final EventListenerList listenerList = new EventListenerList(); public void addChangeListener(ChangeListener listener) { listenerList.add(ChangeListener.class, listener); } public void removeChangeListener(ChangeListener listener) { listenerList.remove(ChangeListener.class, listener); } protected void fireChanged() { final ChangeEvent event = new ChangeEvent(this); final Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener) listeners[i + 1]).stateChanged(event); } } } public abstract boolean accept(T object); } 22 Hortis GRC SA - www.hortis.ch Collections & Generics

Exemple: utilisation filtre public boolean collect(List<D> adaptedObjects, IObjectListModel<? extends D> model) { final boolean added = false; for (final D object : model) { if (filter.accept(object)) { adaptedObjects.add(object); } } return added; } 23 Hortis GRC SA - www.hortis.ch Collections & Generics

Exemple: binding sur une sous-classe public class WayPointDifferentiator extends AbstractNamedAdaptationDataDifferentiator<WayPoint> { public final static WayPointDifferentiator instance = new WayPointDifferentiator(); private WayPointDifferentiator() { super(); } @Override public boolean equals(final WayPoint o1, final WayPoint o2) { return super.equals(o1, o2) && (o1 == null || valueEquals(o1.getArea(), o2.getArea())); } @Override public Class<WayPoint> getObjectClass() { return WayPoint.class; } @Override protected void collectAccessors(ArrayList<String> accessorList) { super.collectAccessors(accessorList); accessorList.add(quot;ShortNamequot;); accessorList.add(quot;Wgs84Latitudequot;); accessorList.add(quot;Wgs84Longitudequot;); } } 24 Hortis GRC SA - www.hortis.ch Collections & Generics

Exemple: binding sur une méthode public abstract class AbstractAdaptationData<T> implements Serializable, IVersionable<T>, Comparable<T> { public static <D extends Comparable<D>> int compare(final D v1, final D v2) { if (v2 == null) { return v1 == null ? 0 : 1; } else if (v1 == null) { return -1; } return v1.compareTo(v2); } 25 Hortis GRC SA - www.hortis.ch Collections & Generics

Exemple: binding sur une méthode public <T extends AbstractAdaptationData<T>> void loadDescriptorData( final AdaptationDataManager manager, final AdaptationDataRepository dataRepository, final AbstractAdaptationDataDescriptor<T> _descriptor, final SubtableController _subtableController, final T selectedObject, final boolean activateSearchField) { setName(_descriptor.getName()); final ObjectTableModel<T> tableModel = _descriptor.getTableModel(manager, selectedObject); tableModel.setResourceBundle(manager.getResourceBundle()); table = new JTableWithToolTips(tableModel); table.setName(_descriptor.getName()); final String searchColumn = _descriptor.getSearchColumn(); MutableDynamicTableFilter<T> dynamicTableFilter = null; MutableDynamicTableSorter<T> dynamicTableSorter = null; final DefaultColumnFilterFactory<T> filterFactory = _descriptor.getFilterFactory(manager); 26 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 27 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 28 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire ClassCastException 29 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 30 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 31 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 32 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 33 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 34 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 35 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 36 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 37 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 38 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 39 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 40 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 41 Hortis GRC SA - www.hortis.ch Collections & Generics

Questionaire 42 Hortis GRC SA - www.hortis.ch Collections & Generics

Add a comment

Related presentations

Presentación que realice en el Evento Nacional de Gobierno Abierto, realizado los ...

In this presentation we will describe our experience developing with a highly dyna...

Presentation to the LITA Forum 7th November 2014 Albuquerque, NM

Un recorrido por los cambios que nos generará el wearabletech en el futuro

Um paralelo entre as novidades & mercado em Wearable Computing e Tecnologias Assis...

Microsoft finally joins the smartwatch and fitness tracker game by introducing the...

Related pages

System.Collections.Generic Namespace

The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed ...
Read more

System.Collections.Generic-Namespace

Der System.Collections.Generic-Namespace enthält Schnittstellen und Klassen, die generische Auflistungen definieren. Mit diesen können Benutzer stark ...
Read more

Introduction to Collections & Generics in Java | Udemy

Please confirm that you want to add Introduction to Collections & Generics in Java to your Wishlist.
Read more

Tutorials - Introduction to Collections & Generics in Java

[img] Introduction to Collections & Generics in Java MP4 | Video: AVC 1280x720 | Audio: AAC 44KHz 2ch | Duration: 2 Hours | 486 MB Genre: eLearning |...
Read more

C# Best Practices: Collections and Generics | Pluralsight

Hello! My name is Deborah Kurata and I'd like to welcome you to my course: "C# Best Practices: Collections and Generics" from Pluralsight. Ah generics ...
Read more

Java Collections Tutorial - Jenkov.com

The fifth text in this Java Collections tutorial covers how to use Generics in Java Collections. Generics is very useful when working with Java's ...
Read more

Java Tutorial - Collections and Generics - Generics - Java 6

Creating A Folder For Our Collections/Generics Source Files. As we are about to write our first code of a new section we will create a folder for our ...
Read more

Collections Generics, internes Verhalten - java-forum.org

Diskutiere Generics, internes Verhalten im Forum Allgemeine Java-Themen - Hallo , ich hätte eine Frage zu Java Generics. Ich weiß das die ...
Read more

Generics - java.silke-wingens.de

Aufgaben, Collections, Generics, Wildcard No Comments ...
Read more

Java collections framework - Wikipedia, the free encyclopedia

Java collections framework is extended by the Apache Commons Collections library, which adds collection types such as a bag and bidirectional map, ...
Read more