Interfacce Interfacce Un interface una collezione di firme

  • Slides: 37
Download presentation
Interfacce

Interfacce

Interfacce Un interface è una collezione di firme di metodi (senza implementazione). Una interfaccia

Interfacce Un interface è una collezione di firme di metodi (senza implementazione). Una interfaccia può dichiarare costanti.

Interfacce C 1 I 1 C 2 I 2

Interfacce C 1 I 1 C 2 I 2

Esempio di interface package strutture; public interface Stack{ public int estrai(); public void insert(int

Esempio di interface package strutture; public interface Stack{ public int estrai(); public void insert(int z); } package strutture; public class Pila implements Stack{ … } package strutture; public class Coda extends Pila{ … }

Interfacce Le interfacce possono essere usate come C 1 I 2 “tipi” I 1

Interfacce Le interfacce possono essere usate come C 1 I 2 “tipi” I 1 x = new C 2(); // I 1 x = new I 1(); NO!! C 2

public static void main(String args[]) { try { Usare Stack s=null; Pile e int

public static void main(String args[]) { try { Usare Stack s=null; Pile e int type=0; do { Code try { type =Integer. parse. Int( JOption. Pane. show. Input. Dialog( "Pila (1) o Coda (2)? ")); } catch (Exception e) {type=0; } } while (type<1 || type>2); switch (type) { case 1: s=new Pila(); break; case 2: s=new Coda(); break; } … }

Collections

Collections

Collections Una collection è un oggetto che ragguppa elementi multipli (anche eterogenei) in una

Collections Una collection è un oggetto che ragguppa elementi multipli (anche eterogenei) in una singola entità. Collections sono usate per immagazzinare, recuperare e trattare dati, e per trasferire gruppi di dati da un metodo ad un altro. Tipicamente rappresentano dati che formano gruppi “naturali”, come una mano di poker (una collection di carte), un mail folder (a collection di e-mail), o un elenco telefonico (una collection di mappe nomenumero).

Collections Famework A collections framework is a unified architecture for representing and manipulating collections.

Collections Famework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain three things: Interfaces: abstract data types representing collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages like Java, these interfaces generally form a hierarchy. Implementations: concrete implementations of the collection interfaces. In essence, these are reusable data structures. Algorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. These algorithms are said to be polymorphic because the same method can be used on many different implementations of the appropriate collections interface. In essence, algorithms are reusable functionality.

Core Collections Interfaces Occorre importare java. util. *

Core Collections Interfaces Occorre importare java. util. *

Core Collections Interfaces A Collection represents a group of objects, known as its elements.

Core Collections Interfaces A Collection represents a group of objects, known as its elements. Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered.

Core Collections Interfaces A Set is a collection that cannot contain duplicate elements

Core Collections Interfaces A Set is a collection that cannot contain duplicate elements

Core Collections Interfaces A List is an ordered collection (sometimes called a sequence). Lists

Core Collections Interfaces A List is an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the List each element is inserted. The user can access elements by their integer index (position).

Core Collections Interfaces A Map is an object that maps keys to values. Maps

Core Collections Interfaces A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value.

Core Collections Interfaces Implementations Hash Table Set Interfac es Hash. Set List Ma p

Core Collections Interfaces Implementations Hash Table Set Interfac es Hash. Set List Ma p Resizable Array Balanced Tree. Set Linked. Li st Array. List Hash. Map Linked List Tree. Map

Collection: Basic operations int size(); boolean is. Empty(); boolean contains(Object element); boolean add(Object element);

Collection: Basic operations int size(); boolean is. Empty(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); Iterator iterator();

Collection: basic operations The add method is defined generally enough so that it makes

Collection: basic operations The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't. It guarantees that the Collection will contain the specified element after the call completes, and returns true if the Collection changes as a result of the call. The remove method is defined to remove a single instance of the specified element from the Collection, assuming the Collection contains the element, and to return true if the Collection was modified as a result.

The Iterator interface public interface Iterator { n boolean has. Next(); n Object next();

The Iterator interface public interface Iterator { n boolean has. Next(); n Object next(); n void remove(); } has. Next returns true if there are more elements in the Collection next() returns the next element in the Collection remove() method removes from the underlying Collection the last element that was returned by next. The remove method may be called only once per call to next, and throws an exception if this condition is violated.

Using Iterators void filter(Collection x) { Iterator i=x. iterator(); n n while (i. has.

Using Iterators void filter(Collection x) { Iterator i=x. iterator(); n n while (i. has. Next()) { if (!cond(i. next())) i. remove(); } cond(Object o) è un NOSTRO metodo nel quale noi implementiamo il controllo della condizione che decide se tenere o meno l’elemento } The code is polymorphic: it works for any Collection that supports element removal, regardless of implementation. That's how easy it is to write a polymorphic algorithm under the collections framework!

Collection: bulk operations // Bulk operations boolean contains. All(Collection c); boolean add. All(Collection c);

Collection: bulk operations // Bulk operations boolean contains. All(Collection c); boolean add. All(Collection c); boolean remove. All(Collection c); boolean retain. All(Collection c); void clear(); // Array Operations Object[] to. Array(); Object[] to. Array(Object a[]);

Collection: bulk operations add. All: Adds all of the elements in the specified Collection

Collection: bulk operations add. All: Adds all of the elements in the specified Collection to the target Collection. remove. All: Removes from the target Collection all of its elements that are also contained in the specified Collection. retain. All: 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 add. All, remove. All, and retain. All methods all return true if the target Collection was modified in the process of executing the operation. contains. All: Returns true if the target Collection contains all of the elements in the specified Collection (c). clear: Removes all elements from the Collection.

Collection: Array operations Object[] to. Array(); Object[] to. Array(Object a[]); Perché Object[]? Ricordate il

Collection: Array operations Object[] to. Array(); Object[] to. Array(Object a[]); Perché Object[]? Ricordate il Principio di sostituzione Di Liskov! 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. to. Array(); 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. to. Array(new String[0]); Notate il cast!

Set: Interface A Set is a Collection that cannot contain duplicate elements. Set models

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.

Set: bulk operations The bulk operations are particularly well suited to Sets: they perform

Set: bulk operations The bulk operations are particularly well suited to Sets: they perform standard set-algebraic operations. Suppose s 1 and s 2 are Sets. s 1. contains. All(s 2): Returns true if s 2 is a subset of s 1. add. All(s 2): Transforms s 1 into the union of s 1 and s 2. s 1. retain. All(s 2): Transforms s 1 into the intersection of s 1 and s 2. s 1. remove. All(s 2): Transforms s 1 into the (asymmetric) set difference of s 1 and s 2. (the set difference of s 1 - s 2 is the set containing all the elements found in s 1 but not in s 2. ) Nota: i metodi sono gli stessi di Collection Ma la semantica è ridefinita!

List A List is an ordered Collection (sometimes called a sequence). Lists may contain

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: w Positional Access: manipulate elements based on their numerical position in the list. w Search: search for a specified object in the list and return its numerical position. w List Iteration: extend Iterator semantics to take advantage of the list's sequential nature. w Range-view: perform arbitrary range operations on the list. NOTA: aggiunge metodi addizionali a Collection!

List: Interface // Positional Access Object get(int index); Object set(int index, Object element); void

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 add. All(int index, Collection c); // Search int index. Of(Object o); int last. Index. Of(Object o);

List: Interface // Iteration List. Iterator list. Iterator(); List. Iterator list. Iterator(int index); //

List: Interface // Iteration List. Iterator list. Iterator(); List. Iterator list. Iterator(int index); // Range-view List sub. List(int from, int to);

Collections è una classe che contiene metodi di utilità e costanti di servizio, tra

Collections è una classe che contiene metodi di utilità e costanti di servizio, tra cui w 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. ) w shuffle(List): Randomly permutes the elements in a List. w reverse(List): Reverses the order of the elements in a List. w fill(List, Object): Overwrites every element in a List with the specified value. w copy(List dest, List src): Copies the source List into the destination List. w binary. Search(List, Object): Searches for an element in an ordered List using the binary search algorithm. List card. Deck=new Array. List(); … Collections. shuffle(card. Deck);

Empty Collections The Collections class provides three constants, representing the empty Set, the empty

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.

Object ordering There are two ways to order objects: The Comparable interface provides automatic

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.

Object ordering with Comparable A List l may be sorted as follows: Collections. sort(l);

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.

Comparable Interface int compare. To(Comparable o) n Compares this object with the specified object

Comparable Interface int compare. To(Comparable o) n 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. n Definisce l’”ordinamento naturale” per la classe implementante.

Comparable Interface Class Point implements Comparable { int x; int y; . . int

Comparable Interface Class Point implements Comparable { int x; int y; . . int compare. To(Point p) { // ordino sulle y retval=y-p. y; // a partità di y ordino sulle x if (retval==0) retval=x-p. x; return retval; } p 1 p 2 p 1 <p 2

Comparator Interface int compare(T o 1, T o 2) Compares its two arguments for

Comparator Interface int compare(T o 1, T o 2) Compares its two arguments for order. class Named. Point. Comparator. By. XY implements Comparator { int compare (Named. Point p 1, Named. Point p 2) { // ordino sulle y retval=p 1. y-p 2. y; // a partità di y ordino sulle x if (retval==0) retval=p 1. x-p 2. x; return retval; }

Comparator Interface class Named. Point. Comparator. By. Name implements Comparator { int compare (Named.

Comparator Interface class Named. Point. Comparator. By. Name implements Comparator { int compare (Named. Point p 1, Named. Point p 2) { //usa l’ordine lessicografico delle stringhe return (p 1. get. Name(). compare. To(p 2. get. Name())); } }

Comparator Interface. . . In un metodo di un altra classe: // sia c

Comparator Interface. . . In un metodo di un altra classe: // sia c una Collection di Named. Points boolean condition=…; Comparator cmp= null; if (condition) cmp= new Named. Point. Comparator. By. Name(); else cmp= new Named. Point. Comparator. By. XY(); List x = new Array. List(c); Collections. sort(x, cmp); Ordina la collezione usando il comparatore scelto

import java. util. *; class Emp. Comparator implements Comparator { public int compare(Object o

import java. util. *; class Emp. Comparator implements Comparator { public int compare(Object o 1, Object o 2) { Employee. Record r 1 = (Employee. Record) o 1; Employee. Record r 2 = (Employee. Record) o 2; return r 2. hire. Date(). compare. To(r 1. hire. Date()); }} class Emp. Sort { Emp. Sort() { Collection employees =. . . ; // Employee Database List emp = new Array. List(employees); Collections. sort(emp, new Emp. Comparator()); System. out. println(emp); } public static void main(String args[ ]) {new Emp. Sort(); } } Lettura di int