Sie sind auf Seite 1von 39

Strutture dati

Strutture e libreria standard


Linked lists
Iterators
Stack e Queue
Set e map

Abbiamo gi visto
isto . . .

Una linked list un insieme di nodi ognuno dei quali ha

una referenza al p
prossimo nodo

Java's LinkedList class


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

LinkedList<Product>
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()

List Iterator
Li
ListIterator
tIt
t
Da accesso agli elementi di una lista
Incapsula
I
l una qualsiasi
l i i posizione
i i
della
d ll lista
li
Protegge la lista stessa

Una vista concettuale

List Iterator

Una sorta di puntatore fra due elementi di una lista


Come il cursore di editor di testo . . .
Il metodo listIterator di LinkedList crea e

restituisce un iterator

LinkedList<String> employeeNames = . . .;
ListIterator<String>
g iterator=employeeNames.listIterator();
p y
();
6

List Iterator
Inizialmente
I i i l
posizionato
i i
prima
i
del
d l primo
i
elemento
l
Il metodo next sposta literator
iterator.next();

next lancia una eccezione NoSuchElementException

se si gi oltrepassato il limite della lista


hasNext vero se la lista ha ancora elementi
if (it
(iterator.hasNext())
t
h N t())
iterator.next();
7

List Iterator

Otre ad avanzare, il metodo next restituisce lelemento che si

oltrepassa
lt

while iterator.hasNext()
{
String name = iterator
iterator.next();
next();
Do something with name
}

List Iterator
Versione breve:
for (String name : employeeNames)
{
Do something with name
}

in realt un tale loop usa un iterator

List Iterator

LinkedList in realt una doubly linked list


Ci sono due links:
Il prossimo
Il precedente

Metodi:
hasPrevious
previous

10

Aggiungere
gg g
/ rimuovere
elementi
Il metodo add:
Aggiunge un elemento dopo la posizione dell
dell

iterator
Muove lliterator
iterator dopo lelemento
l elemento inserito
iterator.add("Juliet");

11

Aggiungere
gg g
/ rimuovere
elementi
Il metodo remove
Rimuove lelemento
l elemento che era stato restituito

dallultima call a next o previous

//Remove all names that fulfill a certain condition


while (iterator.hasNext())
{
String name = iterator.next();
if (name fulfills condition)
();
iterator.remove();
}
12

Aggiungere
gg g
/ rimuovere
elementi
Attenzione alle invocazioni di remove:
Pu essere invocato una sola volta dopo linvocazione
l invocazione di

next o previous
Non pu essere invocato immediatamente dopo una call ad

add
Eccezione: IllegalStateException

13

Esempio

ListTester - un programma che:


Inserisce strings in una list
Visita la lista, aggiungendo e rimuovendo elementi
Stampa
St
lla li
lista
t

14

File ListTester.java
01:
02:
03:
04:
05
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:

import java.util.LinkedList;
import java.util.ListIterator;
java util ListIterator;
/**
A program that
h
d
demonstrates the
h LinkedList
i k d i
class
l
*/
public class ListTester
{
public static void main(String[] args)
{
LinkedList<String> staff=new LinkedList<String>();
staff.addLast("Dick");
staff.addLast("Harry");
staff.addLast(
Harry );
staff.addLast("Romeo");
staff.addLast("Tom");
// | in the comments indicates the iterator position
15

File ListTester.java
ListTester java
19:
20:
21:
22:
23:
24:
25:
26:
27
27:
28:
29:
30:
31:
32:
33:
34:

ListIterator<String> iterator
= staff.listIterator(); // |DHRT
iterator.next(); // D|HRT
iterator.next(); // DH|RT
// Add more elements after second element
iterator.add("Juliet"); // DHJ|RT
it
iterator.add("Nina");
t
dd("Ni ") // DHJN|RT
iterator.next(); // DHJNR|T
// Remove last traversed element
iterator.remove(); // DHJN|T
16

File ListTester.java
ListTester java

35:
36:
37
37:
38:
39:
40: }

// Print all elements


f
for
(String
(S
i
name : staff)
ff)
System.out.println(name);
}

17

File ListTester.java
ListTester java
Output:

Dick
Harry
Juliet
Nina
Tom

18

A ete gi visto.
Avete
isto . .

Stack: "last in first out"


Queue: "first in first out"

19

Ja a library
Java
librar Stack
Stack
Stack<String> s = new Stack<String>();
s.push("A");
s.push("B");
s.push("C");
// The following loop prints C, B, and A
while (s.size() > 0)
System.out.println(s.pop());

Usa un array per implementare lo stack


Queue: pensata per programmi multithreaded . . .
20

Sets

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

Set

22

Iterator
Per la visita di un set si utilizza un iterator
Lordine di visita NON quello di inserimento
//Creating a hash set
Set<String> names = new HashSet<String>();
//Adding
//
g an element names.add("Romeo");
(
);
//Removing an element names.remove("Juliet");
//Is element in23set
if (names
(names.contains("Juliet")
contains("Juliet") { . . .}
}

Iterator
Iterator<String> iter = names.iterator();
while (iter.hasNext())
(
())
{
String name = iter.next();
Do something with name
}
// Or, using the "for each" loop
for (String name : names)
{
Do something with name
}

24

File SetTester.java
SetTester java
01:
02:
03:
04:
05:
06:
07
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:

import
import
import
import

java.util.HashSet;
java
util HashSet;
java.util.Iterator;
java.util.Scanner;
java util Set;
java.util.Set;

/**
This program demonstrates a set of strings. The user
can add and remove strings.
*/
public class SetTester
{
public static void main(String[] args)
{
Set<String> names = new HashSet<String>();
Scanner in = new Scanner(System.in);
25

File SetTester.java
SetTester java
18:
19:
20:
21:
22:
23:
24
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

boolean done = false;


while (!done)
{
System out print("Add name
System.out.print("Add
name, Q when done: ");
String input = in.next();
if (input.equalsIgnoreCase("Q"))
d
done
= true;
t
else
{
names.add(input);
print(names);
}
}
done = false;
while (!done)
{

26

File SetTester.java
SetTester java
35:
36:
37:
38:
39
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:

System.out.println("Remove name, Q when done");


String input = in.next();
in next();
if (input.equalsIgnoreCase("Q"))
done = true;
else
{
names.remove(input);
print(names);
}
}
}
/**
/
Prints the contents of a set of strings.
@param s a set of strings
*/
/
private static void print(Set<String> s)
{

27

File SetTester.java
SetTester java
53:
54:
55:
56
56:
57:
58:
59:
60:
61: }
62:
63:

System.out.print("{
System
out print("{ ");
for (String element : s)
{
System.out.print(element);
i ( l
)
System.out.print(" ");
}
System.out.println("}");
}

28

File SetTester.java
SetTester java
Add name, Q when done: Dick
{ Dick }
Add name, Q when done: Tom

Output
{ Tom
Dick }
Add name,
, Q when done: Harry
y
{ Harry Tom Dick }
Add name, Q when done: Tom
{ Harry Tom Dick }
Add name, Q when done: Q
Remove name, Q when done: Tom
{ Harry Dick }
Remove name, Q when done: Jerry
{ Harry Dick }
R
Remove
name, Q when
h
d
done: Q
29

Maps
Una
U mappa memorizza
i
coppie
i

(chiave oggetto)
Le chiavi sono uniche
Come per gli insiemi:
Map interface
HashMap
TreeMap

30

Un esempio di una Map

31

Map Classes and Interfaces

32

Esempi

//Changing an existing association

favoriteColor.put("Juliet",Color.RED);
//Removing a key and its associated value

(
)
favoriteColors.remove("Juliet");

33

HashMap
//Creating a HashMap
Map<String, Color> favoriteColors
= new HashMap<String, Color>();

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

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

34

HashMap

//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 coppie

Set<String> keySet = m.keySet();


for (String key : keySet)
{
Color value = m.get(key);
System out println(key + "
System.out.println(key
"->"
>" + value);
}

36

File MapTester.java
p
j
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11
11:
12:
13:
14:
15:
16:
17:

import
import
p
import
import
import

java.awt.Color;
java.util.HashMap;
j
p
java.util.Iterator;
java.util.Map;
java.util.Set;

/**
This program tests a map that maps names to colors
colors.
*/
public class MapTester
{
public static void main(String[] args)
{
Map<String, Color> favoriteColors
= new HashMap<String, Color>();
favoriteColors.put("Juliet", Color.pink);
favoriteColors.put("Romeo", Color.green);
37

File MapTester.java
MapTester java
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28: }

favoriteColors.put("Adam", Color.blue);
favoriteColors.put("Eve", Color.pink);
Set<String> keySet = favoriteColors.keySet();
for (String key : keySet)
{
Color value = favoriteColors.get(key);
System.out.println(key + "->" + value);
}
}

38

File MapTester.java
MapTester java

Romeo->java.awt.Color[r=0,g=255,b=0]

Output
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

Das könnte Ihnen auch gefallen