programmazione 2 - marco ronchetti core collections interfaces

32
1 Fac.Scienze – Università di Trento Programmazione 2 - Marco Ronchetti Implementations Hash Table Resizable Array Balanced Tree Linked List Interfaces Set HashSet TreeSet List ArrayList LinkedList Map HashMap TreeMap Core Collections Interfaces

Upload: others

Post on 16-Oct-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

1 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Implementations Hash Table Resizable Array Balanced Tree Linked List

Interfaces Set HashSet TreeSet List ArrayList LinkedList Map HashMap TreeMap

Core Collections Interfaces

Page 2: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

2 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Fondamenti di Java

Implementazione di Pila e Coda usando le Collection

Page 3: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

3 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

package structures; import java.util.*; public abstract class Stack extends LinkedList { public void inserisci(int x) { Number n = new Number(x); this.add(n); } abstract public int estrai(); }

Stack

Page 4: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

4 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

package structures; class Number { private int n; Number(int n) { this.n = n; } int getInt() { return n; } void setInt(int n) { this.n = n; } }

Number

Page 5: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

5 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

class Coda extends Stack { public int estrai() { Number x = null; Iterator iter = this.iterator(); if (iter.hasNext()) { x = (Number) iter.next(); iter.remove(); } else { System.out.println("Tentativo di estrarre da una Coda vuota");

System.exit(1); } return x.getInt(); } }

Coda

Page 6: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

6 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

class Pila extends Stack { public int estrai() { Number x = null; Iterator iter = this.iterator(); while (iter.hasNext()) { x = (Number) iter.next(); } if (x == null) { System.out.println("Tentativo di estrarre da una Pila vuota");

System.exit(1); } iter.remove(); return x.getInt(); } }

Coda

Page 7: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

7 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

public static void main(String[] args) { Stack s=new Coda(); // Stack s=new Pila(); s.inserisci(1);

s.inserisci(2); s.inserisci(3); for (int k=0;k<=4;k++){ int v=s.estrai(); System.out.println(v); } }

main

1 2 3 Tentativo di estrarre da una Coda vuota

3 2 1 Tentativo di estrarre da una Pila vuota

Page 8: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

8 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

package structures; import java.util.*; public abstract class Stack extends ArrayList { public void inserisci(int x) { Number n = new Number(x); this.add(n); } abstract public int estrai(); }

Stack

e se avessi esteso HashSet?

Page 9: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

9 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Fondamenti di Java

Collection: approfondimenti

Page 10: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

10 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Core Collections Interfaces

Map è un entità che abbina oggetti a chiavi di inserimento/ricerca. Map non puo ̀ contenere chiavi duplicate: ciascuna chiave è univocamente in relazione con un oggetto. Esempi di implementazione: tabelle di hash Esempi concreti: anagrafe, lista clienti…

Page 11: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

11 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Core Collections Interfaces

Page 12: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

12 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Collection: bulk operations addAll: Adds all of the elements in the specified Collection to the target Collection. removeAll: Removes from the target Collection all of its elements that are also contained in the specified Collection. retainAll: Removes from the target Collection all of its elements that are not also contained in the specified Collection. That is to say, it retains only those elements in the target Collection that are also contained in the specified Collection. The addAll, removeAll, and retainAll methods all return true if the target Collection was modified in the process of executing the operation. containsAll: Returns true if the target Collection contains all of the elements in the specified Collection (c). clear: Removes all elements from the Collection.

Page 13: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

13 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Collection: Array operations Object[] toArray(); Object[] toArray(Object a[]); Dump the contents of The Collection c into a newly allocated array of Object whose length is identical to the number of elements in c: Object[] a = c.toArray(); Suppose c is known to contain only strings. Dump the contents of c into a newly allocated array of String whose length is identical to the number of elements in String[] a = (String[]) c.toArray(new String[0]);

Page 14: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

14 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Set: bulk operations The bulk operations are particularly well suited to Sets: they perform standard set-algebraic operations. Suppose s1 and s2 are Sets. s1.containsAll(s2): Returns true if s2 is a subset of s1. s1.addAll(s2): Transforms s1 into the union of s1 and s2. s1.retainAll(s2): Transforms s1 into the intersection of s1 and s2. s1.removeAll(s2): Transforms s1 into the (asymmetric) set difference of s1 and s2. (the set difference of s1 - s2 is the set containing all the elements found in s1 but not in s2.)

Page 15: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

15 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Set: Interface A Set is a Collection that cannot contain duplicate elements. Set models the mathematical set abstraction. The Set interface extends Collection and contains no methods other than those inherited from Collection. It adds the restriction that duplicate elements are prohibited.

Page 16: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

16 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

List A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for: •  Positional Access: manipulate elements based on their numerical position in the list. •  Search: search for a specified object in the list and return its numerical position. •  List Iteration: extend Iterator semantics to take advantage of the list's sequential nature. •  Range-view: perform arbitrary range operations on the list.

Page 17: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

17 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

List: Interface // Positional Access 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); // Search int indexOf(Object o); int lastIndexOf(Object o);

Page 18: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

18 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

List: Interface // Iteration ListIterator listIterator(); ListIterator listIterator(int index); // Range-view

List subList(int from, int to);

previous() hasPrevious() nextIndex() previousIndex()

Page 19: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

19 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Collections Collections è una classe che contiene metodi e costanti di servizio, tra cui • sort(List): Sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.) • shuffle(List): Randomly permutes the elements in a List. • reverse(List): Reverses the order of the elements in a List. • fill(List, Object): Overwrites every element in a List with the specified value. • copy(List dest, List src): Copies the source List into the destination List. • binarySearch(List, Object): Searches for an element in an ordered List using the binary search algorithm.

Page 20: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

20 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Empty Collections The Collections class provides three constants, representing the empty Set, the empty List, and the empty Map Collections.EMPTY_SET Collections.EMPTY_LIST Collections.EMPTY_MAP The main use of these constants is as input to methods that take a Collection of values, when you don't want to provide any values at all.

Page 21: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

21 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

La tassonomia completa

Page 22: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

22 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Fondamenti di Java

Collection: object ordering

Page 23: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

23 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Object ordering There are two ways to order objects: The Comparable interface provides automatic natural order on classes that implement it. The Comparator interface gives the programmer complete control over object ordering. These are not core collection interfaces, but underlying infrastructure.

Page 24: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

24 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Object ordering with Comparable A List l may be sorted as follows: Collections.sort(l); If the list consists of String elements, it will be sorted into lexicographic (alphabetical) order. If it consists of Date elements, it will be sorted into chronological order. How does Java know how to do this? String and Date both implement the Comparable interface. The Comparable interfaces provides a natural ordering for a class, which allows objects of that class to be sorted automatically.

Page 25: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

25 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Comparable Interface int compareTo(Object o)

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Definisce l’”ordinamento naturale” per la classe implementante.

Page 26: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

26 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

public class Car implements Comparable{ public int maximumSpeed=0; public String name; Car(int v,String name) {maximumSpeed=v; this.name=name;} public int compareTo(Object o){ if (!(o instanceof Car)) { System.out.println("Tentativo di comparare mele e pere!"); System.exit(1); } if (maximumSpeed<((Car)o).maximumSpeed) return -1; else return (1); } }

Comparable

Page 27: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

27 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

class TestCar{ List macchine=null; public static void main(String[] args) { new TestCar(); } TestCar(){ macchine=new LinkedList(); Car a=new Car(100,"cinquecento"); macchine.add(a); Car b=new Car(250,"porsche carrera"); macchine.add(b); Car c=new Car(180,"renault Megane"); macchine.add(c); printMacchine(); Collections.sort(macchine); printMacchine(); }

Comparable

Page 28: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

28 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

void printMacchine(){ Iterator i=macchine.iterator(); while (i.hasNext()) { System.out.println(((Car)i.next()).name); } } }

Comparable

Page 29: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

29 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

class Car() { int maximumSpeed; compareTo( }

Page 30: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

30 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Comparable Interface Class Point implements Comparable { int x; int y; .... int compareTo(Object p) { … check if Point… // ordino sulle y retval=y-((Point)p).y; // a partità di y ordino sulle x if (retval==0) retval=x-((Point)p).x; return retval; }

p1

p2

p1 <p2

p1 p2

p1 <p2

Page 31: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

31 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Comparator Interface int compare(T o1, T o2)           Compares its two arguments for order. 

class NamedPointComparatorByXY implements Comparator { int compare (NamedPoint p1, NamedPoint p2) { // ordino sulle y retval=p1.y-p2.y; // a partità di y ordino sulle x if (retval==0) retval=p1.x-p2.x; return retval; }

Page 32: Programmazione 2 - Marco Ronchetti Core Collections Interfaces

32 Fa

c.Sc

ienz

e –

Uni

vers

ità d

i Tre

nto

Programmazione 2 - Marco Ronchetti

Comparator Interface class NamedPointComparatorByName implements Comparator { int compare (NamedPoint p1, NamedPoint p2) { //usa l’ordine lessicografico delle stringhe return (p1.getName().compareTo(p2.getName())); } } ... In un metodo di un altra classe: // sia c una Collection di NamedPoints Comparator cmp1= new NamedPointComparatorByName(); Comparator cmp2= new NamedPointComparatorByXY(); List x = new ArrayList(c); Collections.sort(x,cmp1)