[PDF] [PDF] Java Collection Framework

java util * ▫ Java 5 released ◇ Lots of changes about collections Collection ▫ Group of elements (references to objects) ▫ It is not specified whether they 



Previous PDF Next PDF





[PDF] Java Collection Framework

java util * ▫ Java 5 released ◇ Lots of changes about collections Collection ▫ Group of elements (references to objects) ▫ It is not specified whether they 



[PDF] Les collections en Java - Université de Genève

Les collections en Java - Collection ❖ Définies à partir de la racine Interface Collection ou E est le type des éléments de la collection ❖ Les classes 



[PDF] Microsoft PowerPoint - MVCDataSourceV1ppt - Les pages perso

modèle doit être sous la forme d'un java bean © Philippe GENOUD Collection notesEtudiant (int numEtud, String matiere) void updateNote (Note n)



[PDF] Les collections - IGM

L'interface java util Collection est l'interface de base de toutes les structures de donnée qui stocke des éléments Il existe 4 sous-interfaces – Set, ensemble 



[PDF] (Microsoft PowerPoint - Pr\351sentation_Composite) - DevLOG

Collection; import java util Iterator; public abstract class Component { public void operation(){ System out println("Opération par défaut"); } // Ce sont les objets 



[PDF] JAVA GENERICS

24 mar 2016 · /* Remove o fromthe collection; return true if * the collection is changed */ boolean remove(Object o); } 4 Java Collections



[PDF] Présentation PowerPoint - pagesperso

Syntaxe très proche de C++ et Java • C'est un langage très Java n'a pas de mode unsafe permettant l'arithmétique Implémentation d'une collection de livre



[PDF] Langage JAVA - Erick STATTNER

Sommaire 1 Introduction au concept de POO 2 Classes et Objets 3 Héritage et polymorphisme 4 Collections 5 Interfaces Graphiques 3 



[PDF] OBJECT ORIENTED PROGRAMMING - IARE

A class is thus a collection of objects of similar type for example: mango, apple, and In Java, class “Object” is the base class to all other classes – If we do not 

[PDF] java collections beginners book pdf

[PDF] java collections hands on

[PDF] java collections interview questions pdf

[PDF] java collections lecture notes

[PDF] java collections notes by durga sir

[PDF] java collections problems

[PDF] java collections programming exercises

[PDF] java collections tutorialspoint pdf

[PDF] java collections w3resource

[PDF] java compareto custom object

[PDF] java compareto null object

[PDF] java compareto nullable objects

[PDF] java compareto object method

[PDF] java compareto se8

[PDF] java compareto two objects

Java Collection Framework

Version March 2009

2

Framework

ƒInterfaces (ADT, Abstract Data Types)

ƒImplementations (of ADT)

ƒAlgorithms (sort)

ƒjava.util.*

ƒJava 5 released!

ŠLots of changes about collections

3

Interfaces

Collection

SetList

Map

SortedSet

SortedMap

Group containers

Associative containers

Queue

Iterable

4

Implementations

TreeSet

TreeMapArray

List

Linked

List

HashMap

Linked

HashMap

Linked

HashSet

HashSet

Map

Sorted

Map

Collection

SetList

Sorted

Set

Queue

Priority

Queue 5

Internals

LinkedList

Linked list

LinkedHashMapTreeMapHashMapMap

ArrayListList

LinkedHashSet TreeSetHashSetSet

Hash table

Linked list

Balanced

tree

Resizable

array Hash table interface data structure classes 6

Collection

ƒGroupof elements (referencesto objects)

ƒIt is not specified whether they are

ŠOrdered / not ordered

ŠDuplicated / not duplicated

ƒFollowing constructors are common to all

classes implementing Collection

ŠT()

ŠT(Collection c)

7

Collection interface

ƒint size()

ƒboolean isEmpty()

ƒboolean contains(Object element)

ƒboolean containsAll(Collection c)

ƒboolean add(Object element)

ƒboolean addAll(Collection c)

ƒboolean remove(Object element)

ƒboolean removeAll(Collection c)

ƒvoid clear()

ƒObject[] toArray()

ƒIterator iterator()

8

Collection example

Collection persons =

new LinkedList(); persons.add QHR 3HUVRQ³$OLŃH´

System.out.println( persons.size() );

Collection copy =

new TreeSet(); copy.addAll(persons);//new TreeSet(persons)

Person[] array = copy.toArray();

System.out.println( array[0] );

9 Map

ƒAn object that associates keys to values

HBJB 661 ҧ 3HUVRQ

ƒKeys and values must be objects

ƒKeysmust be unique

ƒOnly one value per key

ƒFollowing constructors are common to all

collection implementers

ŠT()

ŠT(Map m)

10

Map interface

ƒObject put(Object key, Object value)

ƒObject get(Object key)

ƒObject remove(Object key)

ƒboolean containsKey(Object key)

ƒboolean containsValue(Object value)

ƒpublic Set keySet()

ƒpublic Collection values()

ƒint size()

ƒboolean isEmpty()

ƒvoid clear()

11

Map example

Map people =new HashMap(); people.put ³$IF607´ //ssnQHR 3HUVRQ³$OLŃH´ ³6PLPO´ people.put ³5%7*51´ //ssnQHR 3HUVRQ³5RNHUP´ ³*UHHQ´

Person bob = people.get³5%7*51´

if( bob == null)

6\VPHPBRXPBSULQPOQ ³1RP IRXQG´

int populationSize = people.size(); 12

Generic collections

ƒFrom Java 5, all collection interfaces

and classes have been redefined as

Generics

ƒUse of generics lead to code that is

Šsafer

Šmore compact

Šeasier to understand

Šequally performing

13

Generic list -excerpt

public interface List{ void add(E x);

Iterator iterator();

public interface Iterator{

E next();

booleanhasNext(); 14

Example

ƒUsing a list of Integers

ŠWithout generics ( ArrayListlist )

list.add(0, new Integer(42));intn= ((Integer)(list.get(0))).intValue();

ŠWith generics ( ArrayList list )

list.add(0, new Integer(42));intn= ((Integer)(list.get(0))).intValue();

Š+ autoboxing( ArrayList list )

list.add(0,new Integer(42));inttotal = list.get(0).intValue();

Group containers

(Collections)Collection

SetList

SortedSet

Queue

16 List

ƒCan contain duplicateelements

ƒInsertion orderis preserved

ƒUser can define insertion point

ƒElements can be accessed by position

ƒAugments Collection interface

17

List additional methods

ƒObject get(int index)

ƒObject set(int index, Object element)

ƒvoid add(int index, Object element)

ƒObject remove(int index)

ƒboolean addAll(int index, Collection c)

ƒint indexOf(Object o)

ƒint lastIndexOf(Object o)

ƒList subList(int fromIndex, int toIndex)

18

List implementations

ArrayList

ƒget(n)

ŠConstant time

ƒInsert (beginning)

and delete while iterating

ŠLinear

LinkedList

ƒget(n)

ŠLinear time

ƒInsert (beginning)

and delete while iterating

ŠConstant

19

List implementations

ƒArrayList

ŠArrayList()

ŠArrayList(int initialCapacity)

ŠArrayList(Collection c)

Švoid ensureCapacity(int minCapacity)

ƒLinkedList

Švoid addFirst(Object o)

Švoid addLast(Object o)

ŠObject getFirst()

ŠObject getLast()

ŠObject removeFirst()

ŠObject removeLast()

20

Example I

LinkedListll =

new LinkedList(); ll.add(new Integer(10)); ll.add(new Integer(11)); ll.addLast(new Integer(13)); ll.addFirst(new Integer(20)); //20, 10, 11, 13 21

Example II

Car[] garage = new Car[20];

garage[0] = new Car(); garage[1] = new ElectricCar(); garage[2] = new ElectricCar(); garage[3] = new Car(); for(int i=0; iNull pointer error

Listgarage = new ArrayList(20);

garage.set( 0, new Car() ); garage.set( 1, new ElectricCar() ); garage.set( 2, new ElectricCar() ); garage.set( 3, new Car()); for(int i; iCar c = garage.get(i); c.turnOn(); 22

Example III

List l = new ArrayList(2); // 2 refs to null

l.add(new Integer(11)); // 11 in position 0 l.add(0, new Integer(13)); // 11 in position 1 l.set(0, new Integer(20)); // 13 replaced by 20 l.add(9, new Integer(30)); // NO: out of bounds l.add(new Integer(30)); // OK, size extended 23
Queue

ƒCollection whose elements have an

order (

Šnot and ordered collection though

ƒDefines a headposition where is the

first element that can be accessed

Špeek()

Špoll()

24

Queue implementations

ƒLinkedList

Šhead is the first element of the list

ŠFIFO: Fist-In-First-Out

ƒPriorityQueue

Šhead is the smallest element

25

Queue example

Queue fifo =

new LinkedList();

Queue pq =

new PriorityQueue(); fifo.add(3); pq.add(3); fifo.add(1); pq.add(1); fifo.add(2); pq.add(2);

System.out.println(fifo.peek()); // 3

System.out.println(pq.peek());// 1

26
Set

ƒContains no methods other than those

inherited from Collection

ƒadd()has restriction that no duplicate

elementsare allowed

Še1.equals(e2) == false

e1,e2

ƒIterator

ŠThe elements are traversed in no

particular order

The equals() Contract

It is reflexive: x.equals(x) == true

It is symmetric: x.equals(y) == y.equals(x)

It is transitive: for any reference values x, y, and z, if x.equals(y) == true AND y.equals(z) == true => x.equals(z) == true It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true (or false), provided that no information used in equals comparisons on the object is modified. x.equals(null) == false hashCode

The hashCode() contract

The hashCode() method must consistently

return the same int, if no information used in equals() comparisons on the object is modified.

If two objects are equal for equals() method,

then calling the hashCode() method on the two objects must produce the sameintegerresult.

If two objects are unequal for equals() method,

then calling the hashCode() method on the two objects MAY produce distinct integer results. producing distinct intresults for unequal objects may improve the performance of hashtables

HashCode()

equals() and hashcode()

ƒequals() and hashCode() are bound together by

a joint contract that specifies if two objects are considered equal using the equals() method, then they must have identical hashcodevalues.

To be truly safe:

ƒIf override equals(), override hashCode()

ƒObjects that are equals have to return identical hashcodes. 32

SortedSet

ƒNo duplicate elements

ƒIterator

ŠThe elements are traversed according to the

natural ordering(ascending)

ƒAugments Set interface

ŠObject first()

ŠObject last()

ŠSortedSet headSet(Object toElement)

ŠSortedSet tailSet(Object fromElement)

ŠSortedSet subSet(Object from, Object to)

33

Set implementations

ƒHashSetimplements Set

ŠHash tables as internal data structure

(faster)

ƒLinkedHashSetextends HashSet

ŠElements are traversed by iterator

according to the insertion order

ƒTreeSetimplements SortedSet

ŠR-B trees as internal data structure

(computationally expensive) 34

Note on sorted collections

ƒDepending on the constructor used

they require different implementation of the custom ordering

ƒTreeSet()

ŠNatural ordering (elements must be

implementations of Comparable)

ƒTreeSet(Comparator c)

ŠOrdering is according to the comparator

rules, instead of natural ordering

Associative containers

(Maps)

Map

SortedMap

36

SortedMap

ƒThe elements are traversed according

PR POH NH\V· natural ordering

(ascending)

ƒAugments Map interface

ŠSortedMap subMap(K fromKey, K toKey)

ŠSortedMap headMap(K toKey)

ŠSortedMap tailMap(K fromKey)

ŠK firstKey()

ŠK lastKey()

37

Map implementations

ƒAnalogous of Set

ƒHashMapimplements Map

ŠNo order

ƒLinkedHashMapextends HashMap

ŠInsertion order

ƒTreeMapimplements SortedMap

ŠAscending key order

38

HashMap

ƒGet/set takes constant time(in case of

no collisions)

ƒAutomatic re-allocation when load

factor reached

ƒConstructor optional arguments

Šload factor(default = .75)

Šinitial capacity(default = 16)

39

Using HashMap

Map students =

new HashMap(); students.put(³123´,

QHR 6PXGHQP³123´³-RH 6PLPO´

Student s = students.get³123´

for(Student si: students.values()){

Iterators

41

Iterators and iteration

ƒA common operation with collections

is to iterate over their elements

ƒInterface Iterator provides a

transparent means to cycle through all elements of a Collection

ƒKeeps track of last visitedelement of

the related collection

ƒEach time the current element is

queried, it moves on automatically 42

Iterator interface

ƒboolean hasNext()

ƒObject next()

ƒvoid remove()

quotesdbs_dbs14.pdfusesText_20