Conoscere l’uso delle collezioni in Java Conoscere il...

22
1

Transcript of Conoscere l’uso delle collezioni in Java Conoscere il...

1

Conoscere l’uso delle collezioni in JavaComprendere le principali caratteristiche nelle varie

classi di Collection disponibiliSaper individuare quali classi di Collection usare in

casi specificiConoscere il concetto di Generics (programmazione

generica) nel contesto delle Collectiongenerica) nel contesto delle CollectionSaper utilizzare classi genericheComprendere il meccanismo del type checking sulle

classi generiche

2

Framework Collections in Java:API Java http://java.sun.com/

Generics in JavaTutorial Sun (in inglese)

http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

Testo di Riferimento (usato nei corsi precedenti) Horstmann - Concetti di informatica e fondamenti di

Java – Apogeo

3

JCF: Collections in Java

4

Problema: raggruppare un insieme di oggetti insieme eaccedere ad essi secondo regole particolari (per esempiouna Coda).Spessi l’utilizzo degli array non è sufficiente

1. Soluzione 1: Realizzare una propria classe che,utilizzando internamente gli array, fornisce i metodi diaccesso opportuniaccesso opportuni

2. Soluzione 2: Utilizzare classi già pronte fornite da Java,scegliendo quella più opportuna ai propri bisogni

Java fornisce un insieme molto ampio di classi (concrete)in grado di collezionare oggetti fornendo un interfacce(estese dalle proprie classi) relative a Pile, Code, Insiemi,Liste, Mappe, Insiemi ordinati ecc …(JCF) Java Collections Framework

5

Collection:List

ArrayList LinkedList Vector

SetSortedSet SortedSetTreeSet

HashSet LinkedHashSet

Altre interfacce disponibiliQueue,Dequeue,Stack, Map, SortedMap …

6

CollectionGroup of objects, known as its elements. Some collections allow

duplicate elements and others do not. Some are ordered andothers unordered. boolean add(Object e) void clear() boolean contains(Object o) Iterator iterator() boolean remove(Object o) int size()

ListListAn ordered collection (also known as a sequence). The user of this

interface has precise control over where in the list each element isinserted E get(int index) E set(int index, E element)

SetA collection that contains no duplicate elements

SortedSetA collection that contains sorted elements

7

Tutti gli oggetti in java estendono da ObjectE’ corretto scrivere: Object o=new Integer(10);

Le collection di java gestiscono elementi di tipo ObjectEsse possono contenere elementi di tipo object

quindi un qualunque oggetto java può essere aggiunto in unacollezionecollezione

NB: Gli oggetti vengono ritornati come Object e non del loro tipospecifico

ArrayList a=new ArrayList();a.add(new Integer(10));//aggiungo un interoObject elem=a.get(0); //oggetto di tipo Object

Per ottenere il tipo originario è necessario il cast esplicitoInteger i=(Integer) a.get(0);//cast esplicito

8

public class ArrayList extends …boolean add(Object e)

Appends the specified element to the end of thislist.

void add(int index, Object element)Inserts the specified element at the specifiedposition in this list.

Object get(int index)Returns the element at the specified position inthis list.this list.

Object set(int index, Object element)Replaces the element at the specified position inthis list with the specified element.

void clear()Removes all of the elements from this list.

Iterator iterator()Returns an iterator over the elements in this listin proper sequence.

int size()Returns the number of elements in this list.

9

Scrivere un metodo javaint somma(ArrayList a)che somma gli elementi del vettore di interi.

Somma: 22Tempo 5 minuti …

5 3 4 8 2

Tempo 5 minuti …

Suggerimenti: utilizzare i metodi get per ottenere glielementi del vettore e size per conoscere il numero dielementi totali.Usando il cast si possono ottenere gli oggetti del tipo

opportunoIl metodo intValue() della classe Integer permette di

ricavare il tipo int10

public static int somma(ArrayList a){int somma=0;for (int i=0;i<a.size();i++){Integer elem=(Integer)a.get(i)somma=somma+elem.intValue();

//tipo primitivo//tipo primitivo}return somma;

}

11

Modo “universale” per scorrere collezioni di elementi,indipendentemente dalla particolare disposizione deglielementiIl metodo Iterator iterator() è disponibile in tutte

classi che estendono da Collection

IteratorIteratorboolean hasNext()

Returns true if the iteration has more elements.

Object next() Returns the next element in the iteration.

void remove() Removes from the underlying collection the lastelement returned by the iterator (optionaloperation).

12

Scrivere un metodo javaint somma(ArrayList a)che somma gli elementi del vettore di interi utilizzando gli

iteratori.

Somma: 22

5 3 4 8 2

Somma: 22

Tempo 5 minuti …

Suggetimenti: ricavare l’iteratore dall’ArrayList e scorrerel’iteratore mediante un while; per la condizione utilizzareil metodo hasNext() dell’iteratore, next() per averel’elemento corrente

13

public static int somma(ArrayList a){int somma=0;Iterator i=a.iterator();while (i.hasNext()){Integer val=(Integer)i.next();somma=somma+val.intValue();somma=somma+val.intValue();

}return somma;

}

Se volessimo stampare un Set come cambiano lecose?

14

Riepilogo dei metodi principali di alcune classi JCF

Collection<E>List<E>

ArrayList<E> Vector<E>Vector<E> LinkedList<E>

15

public interface Collectionboolean add(Object e)

Appends the specified element to the end of thislist.

void add(int index, Object element)Inserts the specified element at the specifiedposition in this list.

void clear()Removes all of the elements from this list.Removes all of the elements from this list.

Iterator iterator()Returns an iterator over the elements in thislist in proper sequence.

int size()Returns the number of elements in this list.

boolean isEmpty()Returns true if this collection contains noelements.

… altri metodi16

public interface List extends CollectionEreditate da Collection

boolean add(Object e)void add(int index, Object element)void clear()Iterator iterator()int size()boolean isEmpty()

E get(int index)E get(int index)Returns the element at the specified position inthis list.

E remove(int index)Removes the element at the specified position inthis list (optional operation).

E set(int index, E element)Replaces the element at the specified positionin this list with the specified element(optional operation).

… altri metodi17

public class ArrayList …implements ListEreditate da List

boolean add(Object e)void add(int index, Object element)void clear()Iterator iterator()Iterator iterator()int size()boolean isEmpty()E get(int index)E remove(int index)E set(int index, E element)

… altri metodi18

public class Vector …implements ListEreditate da List

boolean add(Object e)void add(int index, Object element)void clear()Iterator iterator()int size()int size()boolean isEmpty()E get(int index)E remove(int index)E set(int index, E element)

… altri metodi

Analogo ad ArrayList ma l’implementazione è thread-safe ed è in genere più lenta

19

public class LinkedList …implements ListEreditate da List

boolean add(Object e)void add(int index, Object element)void clear()Iterator iterator()int size()boolean isEmpty()E get(int index)E get(int index)E remove(int index)E set(int index, E element)

E getFirst()Returns the first element in this list.

E getLast()Returns the last element in this list.

… altri metodi

NB: L’implementazione di get e set hanno costo O(n)20

La mancanza di un controllo sui tipi porta ad alcuniproblemi:

1. Necessità di ricorrere al cast degli elementi anchequando il tipo di elementi è notoArrayList a=new ArrayList();a.add(new Integer(10));......Integer i=(Integer)a.get(0);

2. Possibili cast degli elementi a tipi non correttiArrayList a=new ArrayList();a.add(new Integer(10));...String i=(String)a.get(0);//eccezione!!!

21

3. Nessun controllo sui tipi di dati inseriti all’internodi un vettoreArrayList a=new ArrayList();a.add(new Integer(10));...a.add(new String(“paperino”));//?Integer i=(Integer)a.get(0);//OKInteger j=(Integer)a.get(1);//cast exceptionInteger j=(Integer)a.get(1);//cast exception

4. Poca chiarezza sul tipo di dati trattati1. public static ArrayList calcolaQualcosa()

//che tipi contiene?

NB: In tutti i casi, il codice risulta sintatticamente correttoe non viene segnalato alcun errore dal compilatore.L’errore viene scoperto solo a Runtime!

22