39
Strutture dati Strutture dati Strutture e libreria standard Linked lists Iterators Iterators Stack e Queue Set e map 1

PRG OO 16 DataStructure

Embed Size (px)

DESCRIPTION

Data StructureProgrammazione Object Oriented JavaStrutture DatiLinkedListSimpleListArrayListAlberi e GrafiSetHashSetTreeSet

Citation preview

  • Strutture datiStrutture dati

    Strutture e libreria standard

    Linked lists

    Iterators Iterators

    Stack e Queue

    Set e map

    1

  • Abbiamo gi isto Abbiamo gi visto . . .

    Una linked list un insieme di nodi ognuno dei quali ha una referenza al prossimo nodop

    2

  • Java's LinkedList classJava's LinkedList class

    E una classe generica E necessario specificare il tipo degli elementi:LinkedList

    Package: java.util Semplicissimo accedere al primo ed allultimo elemento

    void addFirst(E obj)void addLast(E obj)E getFirst()E getLast()g ()E removeFirst()E removeLast() 3

  • List IteratorList Iterator

    Li tIt t ListIterator Da accesso agli elementi di una lista

    I l l i i i i d ll li Incapsula una qualsiasi posizione della lista Protegge la lista stessa

    4

  • Una vista concettualeUna vista concettuale

    5

  • List IteratorList Iterator

    Una sorta di puntatore fra due elementi di una lista Come il cursore di editor di testo Come il cursore di editor di testo . . .

    Il metodo listIterator di LinkedList crea e restituisce un iterator

    LinkedList employeeNames = . . .;ListIterator iterator=employeeNames.listIterator();g p y ();

    6

  • List IteratorList Iterator

    I i i l i i i d l i l Inizialmente posizionato prima del primo elemento Il metodo next sposta literator

    iterator.next();

    next lancia una eccezione NoSuchElementExceptionse si gi oltrepassato il limite della lista

    hasNext vero se la lista ha ancora elementiif (it t h N t())if (iterator.hasNext())

    iterator.next();7

  • List IteratorList Iterator

    Otre ad avanzare, il metodo next restituisce lelemento che si lt oltrepassa

    while iterator.hasNext(){

    String name = iterator next();String name = iterator.next();Do something with name

    }

    8

  • List IteratorList Iterator

    Versione breve: for (String name : employeeNames)for (String name : employeeNames){

    Do something with name}

    in realt un tale loop usa un iterator

    }

    in realt un tale loop usa un iterator

    9

  • List IteratorList Iterator

    LinkedList in realt una doubly linked list Ci sono due links: Ci sono due links:

    Il prossimo Il precedente Il precedente

    Metodi: hasPrevious previous

    10

  • Aggiungere / rimuovere gg gelementi

    Il metodo add: Aggiunge un elemento dopo la posizione dell Aggiunge un elemento dopo la posizione dell

    iterator

    Muove literator dopo lelemento inserito Muove l iterator dopo l elemento inserito

    iterator.add("Juliet");

    11

  • Aggiungere / rimuovere gg gelementi

    Il metodo remove Rimuove lelemento che era stato restituito Rimuove l elemento che era stato restituito

    dallultima call a next o previous//Remove all names that fulfill a certain conditionwhile (iterator.hasNext()){

    String name = iterator.next();if (name fulfills condition)

    iterator.remove();();}

    12

  • Aggiungere / rimuovere gg gelementi

    Attenzione alle invocazioni di remove: Pu essere invocato una sola volta dopo linvocazione di Pu essere invocato una sola volta dopo l invocazione dinext o previous

    Non pu essere invocato immediatamente dopo una call ad Non pu essere invocato immediatamente dopo una call ad add

    Eccezione: IllegalStateException Eccezione: IllegalStateException

    13

  • EsempioEsempio

    ListTester - un programma che: Inserisce strings in una list Inserisce strings in una list Visita la lista, aggiungendo e rimuovendo elementi St l li t Stampa la lista

    14

  • File ListTester.javaFile ListTester.java01: import java.util.LinkedList;02: import java util ListIterator;02: import java.util.ListIterator;03: 04: /**05 h d h i k d i l05: A program that demonstrates the LinkedList class06: */07: public class ListTester08: { 09: public static void main(String[] args)10: { {11: LinkedList staff=new LinkedList();12: staff.addLast("Dick");13: staff.addLast("Harry");13: staff.addLast( Harry );14: staff.addLast("Romeo");15: staff.addLast("Tom");16:16: 17: // | in the comments indicates the iterator position18: 15

  • File ListTester javaFile ListTester.java19: ListIterator iterator20: = staff.listIterator(); // |DHRT21: iterator.next(); // D|HRT21: iterator.next(); // D|HRT22: iterator.next(); // DH|RT23: 24: // Add more elements after second element24: // Add more elements after second element25:26: iterator.add("Juliet"); // DHJ|RT27 it t dd("Ni ") // DHJN|RT27: iterator.add("Nina"); // DHJN|RT28:29: iterator.next(); // DHJNR|T30: 31: // Remove last traversed element 32: 33: iterator.remove(); // DHJN|T34: 16

  • File ListTester javaFile ListTester.java

    35: // Print all elements36: 37 f (S i ff)37: for (String name : staff)38: System.out.println(name);39: }40: }

    17

  • File ListTester javaFile ListTester.java Output: Output:

    DickHarryJulietNinaTom

    18

  • A ete gi isto Avete gi visto. . .

    Stack: "last in first out"

    Queue: "first in first out"

    19

  • Ja a librar StackJava library Stack

    StackStack s = new Stack();s.push("A");s.push("B");s.push("C");// The following loop prints C, B, and Awhile (s.size() > 0)

    System.out.println(s.pop());

    Usa un array per implementare lo stack

    Queue: pensata per programmi multithreaded . . . 20

  • SetsSets

    Set: collezione non ordinata di oggetti . . .

    La standard Java library fornisce due implementazioni del set, basate su due strutture diverse

    HashSet TreeSet

    Entrambe implementano la stessa interfaccia Set

    21

  • SetSet

    22

  • Iterator

    Per la visita di un set si utilizza un iterator

    Lordine di visita NON quello di inserimento

    //Creating a hash set Set names = new HashSet();Set names new HashSet();

    //Adding an element names.add("Romeo");// g ( );

    //Removing an element names.remove("Juliet");

    23//Is element in set if (names contains("Juliet") { }if (names.contains("Juliet") { . . .}

  • Iterator Iterator

    Iterator iter = names.iterator(); while (iter.hasNext()) ( ()){

    String name = iter.next();Do something with nameDo something with name

    }

    // Or, using the "for each" loopfor (String name : names) {{

    Do something with name }

    24

  • File SetTester javaFile SetTester.java01: import java util HashSet;01: import java.util.HashSet;02: import java.util.Iterator;03: import java.util.Scanner;04: import java util Set;04: import java.util.Set;05: 06: 07 /**07: /**08: This program demonstrates a set of strings. The user09: can add and remove strings.10: */11: public class SetTester12: {13: public static void main(String[] args)14: {15: Set names = new HashSet();15: Set names new HashSet();16: Scanner in = new Scanner(System.in);17: 25

  • File SetTester javaFile SetTester.java18: boolean done = false;18: boolean done false;19: while (!done)20: {21: System out print("Add name Q when done: ");21: System.out.print("Add name, Q when done: ");22: String input = in.next();23: if (input.equalsIgnoreCase("Q")) 24 d t24: done = true;25: else26: {27: names.add(input);28: print(names);29: }30: }31:32: done = false;32: done false;33: while (!done)34: { 26

  • File SetTester javaFile SetTester.java35: System.out.println("Remove name, Q when done");36: String input = in next();36: String input = in.next();37: if (input.equalsIgnoreCase("Q")) 38: done = true;39 else39: else40: {41: names.remove(input);42: print(names);43: }44: }45: }46: 47: /**/48: Prints the contents of a set of strings.49: @param s a set of strings50: */50: /51: private static void print(Set s)52: { 27

  • File SetTester javaFile SetTester.java53: System out print("{ ");53: System.out.print("{ ");54: for (String element : s)55: {56 i ( l )56: System.out.print(element);57: System.out.print(" ");58: }59: System.out.println("}"); 60: }61: }}62:63:

    28

  • File SetTester javaFile SetTester.javaAdd name, Q when done: Dick{ Dick } OutputAdd name, Q when done: Tom{ Tom Dick }Add name, Q when done: Harry, Q y{ Harry Tom Dick }Add name, Q when done: Tom{ Harry Tom Dick }{ Harry Tom Dick }Add name, Q when done: QRemove name, Q when done: Tom{ Harry Dick }{ Harry Dick }Remove name, Q when done: Jerry{ Harry Dick }R Q h d QRemove name, Q when done: Q

    29

  • MapsMaps

    U i i Una mappa memorizza coppie (chiave oggetto)

    Le chiavi sono uniche Le chiavi sono uniche

    Come per gli insiemi: Map interface HashMap HashMap TreeMap

    30

  • Un esempio di una MapUn esempio di una Map

    31

  • Map Classes and InterfacesMap Classes and Interfaces

    32

  • EsempiEsempi

    //Changing an existing associationfavoriteColor.put("Juliet",Color.RED);

    //Removing a key and its associated valuefavoriteColors.remove("Juliet");( )

    33

  • HashMapHashMap//Creating a HashMapMap favoriteColors

    = new HashMap();

    //Adding an association favoriteColors.put("Juliet", Color.PINK);

    //Ch i i ti i ti//Changing an existing association favoriteColor.put("Juliet",Color.RED);

    34

  • HashMapHashMap

    //Getting the value associated with a key Color julietsFavoriteColor

    = favoriteColors get("Juliet");= favoriteColors.get("Juliet");

    //Removing a key and its associated value favoriteColors.remove("Juliet");

    35

  • Stampare tutte le coppieStampare tutte le coppie

    Set keySet = m.keySet(); for (String key : keySet)for (String key : keySet) {

    Color value = m.get(key); System out println(key + " >" + value);System.out.println(key + "->" + value);

    }

    36

  • File MapTester.javap j01: import java.awt.Color;02: import java.util.HashMap;p j p03: import java.util.Iterator;04: import java.util.Map;05: import java.util.Set;05: import java.util.Set;06: 07: /**08: This program tests a map that maps names to colors08: This program tests a map that maps names to colors.09: */10: public class MapTester11 {11: {12: public static void main(String[] args)13: { 14: Map favoriteColors15: = new HashMap();16: favoriteColors.put("Juliet", Color.pink);17: favoriteColors.put("Romeo", Color.green);

    37

  • File MapTester javaFile MapTester.java18: favoriteColors.put("Adam", Color.blue);19: favoriteColors.put("Eve", Color.pink);20:21: Set keySet = favoriteColors.keySet();22: for (String key : keySet)23: {23: {24: Color value = favoriteColors.get(key);25: System.out.println(key + "->" + value);26: }26: }27: }28: }

    38

  • File MapTester javaFile MapTester.java

    OutputRomeo->java.awt.Color[r=0,g=255,b=0] Eve->java.awt.Color[r=255,g=175,b=175] Adam->java.awt.Color[r=0,g=0,b=255] Juliet->java.awt.Color[r=255,g=175,b=175]

    39