Вы находитесь на странице: 1из 65

Object Management

1. Association, access control and visibility


2. Data structures
3. Classes for data structures
4. Applications with lists
5. Mappings

Tiberiu Leia: Software engineering Object management

1. Association, access control and visibility


UML notations Representation of Relationships between Classes

Association describes the relations between objects and not between


classes as inheritance (extends).
Asociere = Association
Asociere navigabil = Navigable association
Dependen = Dependency it leads to a design system.
Aggregation relation is one of association!
What does mean: two objects are associated?
What are the usage?
Tiberiu Leia: Software engineering Object management

Association
An association represents a family of links. Binary associations
(with two ends) are normally represented as a line, with each end
connected to a class box. Higher order associations can be drawn
with more than two ends. In such cases, the ends are connected to a
central diamond (aggregation).
An association can be named, and the ends of an association can be
adorned with role names, ownership indicators, multiplicity,
visibility, and other properties.
Associations can only be shown on class diagrams.
Tiberiu Leia: Software engineering Object management

Dependency injection: If an object depends upon having an


instance of some other object then the needed object is "injected"
into the dependent object.
Dependency Injection describes the situation where one object
uses a second object to provide a particular capacity.
Ex.: A database connection is passed as an argument to the
constructor instead of creating one internally.
Source: Wikipedia

Tiberiu Leia: Software engineering Object management

A dependency in the UML exists between two defined elements if


a change to the definition of one may result in a change to the other.
In UML this is indicated by a dashed line pointing from the dependent (or
client) to the independent (or supplier) element.
If more than one client or supplier participates in the dependency, arrows
with their tails on the client elements are connected to the tails of one or
more arrows with their heads on the supplier elements.

Place a small dot on the junction point along with a note on the
dependency.
Dependency is a model-level relationship and not a run-time
relationshipdescribing the need to investigate the model
definition of the client element for possible changes if the model
definition of the supplier element is changed.
Tiberiu Leia: Software engineering Object management

Standard predefined dependencies


UML - defined dependencies include:

call UML2: The client (an operation) may call the supplier (an
operation)
create UML2: The client (a classifier) may create instances of
the supplier (a classifier)
derive UML2: The client (e.g., attribute value, link) may be
computed from the supplier(s)
instantiate UML2: Operations of the client (a classifier) may
create instances of the supplier (a classifier)
refine UML2: The client element(s) are at a "later" semantic
level than the supplier(s)
send UML2: The client (an operation) sends the supplier (a
signal)

Tiberiu Leia: Software engineering Object management

substitute UML2: The client element can replace (under some


circumstances) the supplier
trace UML2: The client elements "trace" to the suppliers.
Typically used for levels of requirements
use UML2: The client element somehow "uses" the supplier

Dependency injection can be achieved by:


setter type methods
by constructors
by interfaces

Tiberiu Leia: Software engineering Object management

association
ClasaA

role
1 *

+atribute: Type = initialValue

ClasaB

+operation(argList): returnType

cardinality
MainClass
+main()

Fig. 1. Exemplu de asociere directionata

How can this be implemented?


Tiberiu Leia: Software engineering Object management

class ClasaA {
ClasaB asoc;
public Atrib attrib=new Atrib();
ClasaA(ClasaB b) {
asoc=b;
.........}
public void metA() {
asoc.metB();//merge?
Atrib x=asoc.atrib;//merge?
}
}

class ClasaB {
public Atrib attrib=new Atrib();
ClasaB() {........}
public void metB() {............}
}
Atrib

ClasaA

ClasaB

+attrib: Atrib

+attrib: Atrib

+metA()

+metA()

TestObjectArray

public class MainClass {


public static void main(String[] args) {
ClasaB refB=new ClasaB();
ClasaA refA=new ClasaA(refB);
refb.metB();
}
}

Tiberiu Leia: Software engineering Object management

+refB: ClasaB
+refA: ClasaA

ClasaA

ClasaB

+atribute: Type = initialValue


+operation(argList): returnType

MainClass
+main()

Fig. 2. Exemplu de asociere (bidirectionala)

How can be programmed if the


object of type ClasaA must be
associated with:
10 objects of type ClasaB

n (unlimited) objects of
type ClasaB

How can this be implemented?

Tiberiu Leia: Software engineering Object management

10

class ClasaA {
ClasaB asocB;
public Atrib attrib=new Atrib();
ClasaA(ClasaB b) {
asocB=b;
.........}
public void metA() {
asoc.metB();
Atrib x=asoc.atrib;
}
}
ClasaA

ClasaB

+atribute: Type = initialValue


+operation(argList): returnType

MainClass

class ClasaB {
public Atrib attrib=new Atrib();
ClasaA asocA;
ClasaB(ClasaA a) {
asocA=a;
........}
public void metB() {............}
}
public class MainClass {
public static void main(String[] args) {
ClasaB refB=new
ClasaB(refA);//???
ClasaA refA=new ClasaA(refB);
refb.metB();
}
}

+main()

Fig. 2. Exemplu de asociere (bidirectionala)

Tiberiu Leia: Software engineering Object management

Does it work ?
11

class ClasaA {
ClasaB asocB;
ClasaA(ClasaB b) {
asocB=b;
.........}
public associateB(ClasaB b) {
asocB=b;
}
public void metA() {
Atrib x=asocB.attrib; //merge?
}
}
public class MainClass {
public static void main(String[] args) {
ClasaB refB=new ClasaB();
ClasaA refA=new ClasaA();
refB.associateA(refA);
refA.associateB(refB);
//call method of refA, refB
}
Tiberiu Leia: Software engineering Object management
}

class ClasaB {
public Atrib attrib=new Atrib();
ClasaA asocA;
ClasaB(ClasaA a) {
asocA=a;
........}
public associateA(ClasaA a) {
asocA=a;
}
public void metB() {
asocA.metA();//merge?
}
}
How can be implemented if an object of
ClasaA must be associated with:
10 objects of ClasaB
n (unlimited) objects of ClasaB
What does it happen if metA() is called
before association?
Class diagrams describe a static
12
situation!

Can an object be associated to more than one object?


Can the same object be aggregated (direct) to more objects?
Can the same object enter
aggregation) of more objects?

in

composition

(indirect

A type of objects can be used in composition of different


aggregates!
Can be created a catalog of aggregates where a type of
object can be used!
Can be created an agenda with the associations of an object!

Tiberiu Leia: Software engineering Object management

13

Access control and visibility


Can be objects methods called without any condition?
Can be accessed the objects state without any restriction?
What is the role of access modifiers?
Accessibility is a static property - that means it cannot be
modified during runtime.
It depends on modifiers.
The assigned names represent an access mode to package
members and to types.
Accessibility affects inheritance of class members, including the
hiding and method overriding.
Tiberiu Leia: Software engineering Object management

14

Access control refers to:


class extending
object construction
field access
method calls

Tiberiu Leia: Software engineering Object management

15

Class accessibility
A high level class can be endowed only with public modifier.
A class that is not public can be used only by instances of other
classes from the same package.
It can be extended by classes of the same package.
A class can be declared public to be accessible by all instances of
all packages.
public modifier for a high level class makes it visible and
accessible everywhere.
A class not declared public is visible only in the package where
it was defined. In a file with more classes only one can be public.
Inner classes may have the modifiers private, protected and
static as any member.
Tiberiu Leia: Software engineering Object management

16

The methods of inner classes declared private cannot be called


from other classes.
Accessibility of fields and methods
The members of a class declared public have global visibility.
A variable declared public is visible (can be accessed) everywhere
in a program where the class is visible.
It is similar for methods.

private accessed only by instances of the classes

Tiberiu Leia: Software engineering Object management

17

Access level

Access allowed for

public
private
protected

All classes, all objects


Only for the current class objects
Accessible for the classes of the same package and
the subclasses outside the package
implicit, <default> Classes of the same package
or friendly

Tiberiu Leia: Software engineering Object management

18

Access table relative to object construction:


Statement
<default>
friendly
static

final
static final

Construction
Each object instance
A single construction
for all the objects of
this type (this class,
only in the class).
For each object
instantiation.
A single construction
for all the objects of
this type

Access
For the object that has declared and
subclasses that instantiate the object
Accessible for all the objects
instantiated with this template

Can be read by all objects, but cannot


be modified by subclasses.
Can be read by all objects, but cannot
be modified by subclasses.

Tiberiu Leia: Software engineering Object management

19

A public method of a superclass can be overwritten only by a


public method. Otherwise the compiler signals an error.

Tiberiu Leia: Software engineering Object management

20

2. Data Structures
a. Arrays
b. Lists
c. Sets
d. Mappings
.

Tiberiu Leia: Software engineering Object management

21

2.1. Data Structures - Arrays


Representation

refArray
insert ?
Types of arrays:
with primitive data
with objects
E.g.. Array:
int[] refTablou=new int[10]; //dimensiunea tabloului este 10 (elemente)
refTablou[0]=2;
refTablou[1]=3;
Tiberiu Leia: Software engineering Object management

22

Construction by enumeration:
int refTablou={2,3,4,1};
int k=refTablou[2];// k=2
Problem: element insertion

Tiberiu Leia: Software engineering Object management

23

Arrays with objects

refTablou

object
reference

insert ?

obiect1:Clasa1
obiect2:Clasa2

Tiberiu Leia: Software engineering Object management

24

Implementation:
Class1 refObiect1=new Class1();
Class1 refObiect2=new Class1();
Arrays with objects of the same type:
Class1[] refTabCuObiecte=new Class1[10];
//add objects in array
refTabCuObiecte[1]=refObiect1;
refTabCuObiecte[2]=refObiect2;
//attach the object to another reference
Class1 ob1=refTabCuObiecte[2];
//the object can be referred by refObiect1 or ob1
Tiberiu Leia: Software engineering Object management

25

Arrays with objects of different types:


Object[] refTabCuObiecte=new Object[10];
//add the object to array
refTabCuObiecte[1]=refObiect1;
refTabCuObiecte[2]=refObiect2;
//Attach the object to another reference
Class1 ob1= (Class1) refTabCuObiecte[2];
//The object can be refered by refObiect1 or ob1

Tiberiu Leia: Software engineering Object management

26

Construction of arrays of different types; 1: Relative objects


public class ClasaBaza
{
public void metA(){
System.out.println("
metA() of ClasaBaza");
}
public void metB(){
System.out.println("
metB() of ClasaBaza");
}
}

public class ClasaA extends


ClasaBaza {
public ClasaA() {
System.out.println(
"Object of ClasaA");
}
public void metA(){
System.out.println("metA()of
ClasaA");
}
public void metB(){
System.out.println("metB()
of ClasaA");
}
}

Tiberiu Leia: Software engineering Object management

27

public class ClasaB extends


ClasaBaza{
public ClasaB(){
ClasaBaza

System.out.println("Object
of ClasaB");
}
public void metA(){
System.out.println("metA()
of ClasaB");
}
public void metB(){
System.out.println("metB()of
ClasaB");
}
}

Tiberiu Leia: Software engineering Object management

+metA()
+metB()

ClasaA
+metA()
+metB()

ClasaB
+metA()
+metB()

TestObjectArray
+ob1: ClasaA
+ob2: ClasaB
+tabCuObiecte: ClasaBaza[10]
+obNou: ???

28

public class TestObjectArray {


public static void main(String[] args) {
ClasaBaza[] tabCuObiecte=new ClasaBaza[10];
ClasaA ob1=new ClasaA();
ClasaB ob2=new ClasaB();
ob1.metA();
ob1.metB();
ob2.metB();
tabCuObiecte[0]=ob1;
tabCuObiecte[1]=ob2;
//
tabCuObiecte[0].metA(); - signals error
//
tabCuObiecte[1].metB(); - signals error
//Asa merge:
ClasaA obNou= (ClasaA) tabCuObiecte[0];
obNou.metA();
obNou.metB();
//Conclusion: cast the object to the appropriate type
}
}
Tiberiu Leia: Software engineering Object management

29

2: Non relative objects


public class ClasaA {
public ClasaA() {
System.out.println
("object ClasaA");
}
public void
metA(){
System.out.println
("metA() of ClasaA");
}
}

public class ClasaB {


public ClasaB(){
System.out.println("Object
ClasaB");
}
public void metB(){
System.out.println("metB()of
clasaB");
}
}

Tiberiu Leia: Software engineering Object management

30

public class TestObjectArray {


public static void main(String[] args) {
Object[] tabCuObiecte=new Object[10];
ClasaA ob1=new ClasaA();
ClasaB ob2=new ClasaB();
ob1.metA();
ob2.metB();
tabCuObiecte[0]=ob1;
tabCuObiecte[1]=ob2;
//
tabCuObiecte[0].metA(); - signals error
//
tabCuObiecte[1].metB(); - signals error
//Asa merge:
ClasaA obNou= (ClasaA) tabCuObiecte[0];
obNou.metA();
//Conclusion: cast the object to the
//appropriate type
}
}
Tiberiu Leia: Software engineering Object management

31

ClasaA
+metA()
+metB()

ClasaB
+metA()
+metB()

TestObjectArray
+tabCuObiecte: Object[10]
+ob1: ClasaA
+ob2: ClasaB
+obNou: ???

Tiberiu Leia: Software engineering Object management

32

Sorting the data of an array


Clasa Arrays
n java.util exist clasa Arrays care are urmtoarele metode statice:
asList(Object[]) returneaz o list de dimensiune fix
binarySearch(byte[], byte) caut n tabloul specificat de octei
valoarea dat de parametrul de tip byte folosind algoritmul de cutare
binar
binarySearch(char[], char) idem pentru tipul char
exist metode similare i pentru celelalte tipuri de date primitive
binarySearch(Object[], Object) idem pentru tipul Object
equals(boolean[], boolean[]) compar dou tablouri i returneaz
true dac tablourile sunt egale
exist metode similare i pentru celelalte tipuri primitive de date
sort(byte[], int, int) sorteaz n ordine cresctoare octeii din tablou
ntre indicii dai.
Tiberiu Leia: Software engineering Object management

33

E.g.:
int[] tabInt=new int[10];
Arrays.fill(tabInt,0,2,5);
Arrays.fill(tabInt,2,5,1);
Arrays.fill(tabInt,4,8,3);
Arrays.fill(tabInt,8,10,2);
Arrays.sort(tabInt,0,9);

Tiberiu Leia: Software engineering Object management

34

2. 2. Data Structures Lists


simple linked
double linked
ring

next
previo
us
refObi

remove ?

insert ?

ect
Head = antet

next

next

next

previous

previous

previous

refObiect

refObiect

refObiec

t
obiect1:Clasa1
obiect2:Clasa2
Tiberiu Leia: Software engineering Object management

obiect3:Clasa3

35

List

PersTelephone

ListNode

+name: String
element +nrTelephone: String

+isEmpty()
+find()
+insert()
+remove()

+toString()
current
n
ListIterator
+retrieve()
+advance()

MainClass

+main()

Fig. 5. Diagrama claselor unei aplicatii care utilizeaza o lista.

Tiberiu Leia: Software engineering Object management

36

Interface Collection
Interfaa Collection din java.util este utilizat pentru a transfera colecii i a
le manevra. Interfaa Collection are definite metodele:
add(Object a) - garanteaz c respectiva colecie are elementul specificat
(returneaz false n caz contrar)
addAll(Collection c) adaug ntreaga colecie c
clear() elimin toate elementele din colecie
contains(Object o) returneaz true dac n colecie exist elementul
specificat
containsAll(Collection c)
equals(Object o)- compar obiectul o dac este egal cu ntreaga colecie
hashCode() returneaz valoarea codului hash pentru colecia curent
isEmpty()
iterator() returneaz un iterator pentru elementele coleciei
remove(Object o)
removeAll(Collection c)
Tiberiu Leia: Software engineering Object management

37

size() returneaz numrul de elemente ale coleciei


toArray() returneaz un tablou coninnd toate elementele coleciei
toArray(Object[] o) returneaz un tablou coninnd toate elementele
coleciei ale cror tip coincide cu cel specificat

Tiberiu Leia: Software engineering Object management

38

Class ArrayList
din java.util implementeaz interfeele Cloneable, Collection, List i
Serializable.
Are constructorii:
ArrayList() creeaz o list vid
ArrayList(Collection c) creeaz o list care include o colecie
ArrayList(int initialCapacity) creeaz o list cu o capacitate
garantat

Tiberiu Leia: Software engineering Object management

39

Clasa ArrayList methods

add(int Index, Object element)- adaug un element ntr-o anumit


poziie
add(Object o) - adaug un element n ultima poziie
addAll(Collection c) - adaug toate elementele din colecie
addAll(int index, Collection c) - adaug toate elementele din
colecie ncepnd cu ultima poziie unde a rmas indicatorul
clear() terge toate elementele
clone()
contains(Object element)
ensureCapacity(int minCapacity)
get(int index)
indexOf(Object element)
isEmpty()
Tiberiu Leia: Software engineering Object management

40

lastIndexOf(Object element)
remove(int index)
removeRange(int fromIndex, int toIndex)
set(int index, Object element)
size() returneaz numrul de elemente
toArray() returneaz un tablou coninnd toate elementele din
list n ordinea corect
toArray(Object[] a)

Tiberiu Leia: Software engineering Object management

41

E.g..:
Collection c1=new ArrayList();
c1.add("nume1");//introduce elemente in
tablou
c1.add("nume2");
c1.add("nume3");
Collection c2=new ArrayList();
c2.add("nume4");//introduce elemente in
tablou
c2.add("nume5");
c2.add("nume6");
c1.addAll(c2);
String st=Collections.max(c1);
Tiberiu Leia: Software engineering Object management

42

Interface ListIterator
Extinde interfaa Iterator. Cu ea se creeaz un iterator pentru liste
care permite traversarea acestora n ambele direcii.
Are metodele:
void add(Object o) insereaz elementul n list
boolean hasNext()
boolean hasPrevious()
Object next()
int nextIndex()
Object previous()
int previousIndex()
void remove()
void set(Object o)
Tiberiu Leia: Software engineering Object management

43

Class LinkedList
void add(int index, Object element) insereaz un element n
poziia specificat
boolean add(Object o) adaug elementul o la coada listei
boolean addAll(Collection c) adaug toate elementele din c
boolean addAll(int index, Collection c) adaug toate elementele
din c la poziia dat de indice
boolean addFirs(Object o)
boolean addLast(Object o)
void clear()
Object clone()
boolean contains(Object o)
boolean containsAll(Collection c)
boolean equals(Object o)
Tiberiu Leia: Software engineering Object management

44

Object get(int index) returneaz elementul din poziia precizat


int hashCode() returneaz valoarea codului hash din list
int indexOf(Object o) returneaz indicele din list unde apare
prima dat elementul precizat
boolean isEmpty()
Iterator iterator() returneaz un iterator al tuturor elementelor
din list
int lastIndexOf(Object o)
ListIterator listIterator () - returneaz un iterator al elementelor
din list ncepnd de la poziia dat
ListIterator listIterator (int index)
Object remove(int index) elimin elementul din poziia
specificat i returneaz obiectul care a fost specificat
Object remove(Object o)
Tiberiu Leia: Software engineering Object management

45

boolean remove(Object o)
Object removeFirst()
boolean removeFirst()
boolean removeAll(Collection c)
boolean retainAll(Collection c) reine numai elementele din list
care sunt coninute n colecia specificat
Object set(int index, Object element) nlocuiete elementul din
poziia specificat cu elementul precizat i returneaz elementul
care era anterior n acea poziie
int size() returneaz numrul de elemente din list
List subList(int from Index, int toIndex) returneaz o imagine a
unei pri din list ntre indicii precizai (exclusiv)
Object toArray() returneaz un tablou coninnd toate elementele
din list
Object[] toArray(Object[] o)
Tiberiu Leia: Software engineering Object management

46

Titanic Problem
Two classes with passengers: Clasa1 and Clasa2
Criteria of the passenger order:
female age 5
male age
E.g. Ana is 33 years old; Dan is 33; Gelu is 26
Order: Gelu < Ana < Dan
Use static method sort(lista, comparator) of Collection.

Tiberiu Leia: Software engineering Object management

47

public class Calator {


String name;
int age;
char sex;
int cls;//clasa 1 sau 2
public Calator(String pers, int v, char s,int c) {
name=new String(pers);
age=v;
sex=s;
cls=c;
}
public String toString(){
return name+"- Age= "+age+", sex="+sex+"; Class
"+cls;
}
}
Tiberiu Leia: Software engineering Object management

48

/* Compare 2 objects x and y with:


* if x<y ==> rez=-1
* if x>y ==> rez=1
* if x=y ==> rez=0 */
import java.util.*;
public class Comparare implements Comparator{
int rez,temp1,temp2;
public int compare(Object x, Object y)
{
Calator unu,doi;
unu=(Calator)x;
doi=(Calator)y;
if(unu.sex=='f') temp1=unu.age-5;
else temp1=unu.varsta;
if(doi.sex=='f') temp2=doi.age-5;
Tiberiu Leia: Software engineering Object management

49

else temp2=doi.age;
if(temp1<temp2) rez=-1;
if(temp1>temp2) rez=1;
if(temp1==temp2) rez=0;
return rez;
}
public boolean equals(Object x)
{
if(temp1==temp2) return true;
else return false;
}
}

Tiberiu Leia: Software engineering Object management

50

/* Titanic*/
import java.util.*;
public class MainClass {
public static void main(String[] args) {
ArrayList cl1=new ArrayList();
ArrayList cl2=new ArrayList();
Calator c1=new Calator("Pop V.",15, 'm',1);
Calator c2=new Calator("Ion A.",20, 'f',2);
Calator c3=new Calator("Nume1 D.",17, 'f',1);
Calator c4=new Calator("Nume2 M.",45, 'm',2);
Calator c5=new Calator("Nume4 G.",23, 'f',2);
Calator c6=new Calator("Nume5 I.",60, 'f',2);
Calator c7=new Calator("Nume6 O.",21, 'm',1);
Calator c8=new Calator("Nume7 X.",54, 'm',1);
cl1.add(c1);
cl2.add(c2);
cl1.add(c3);
cl2.add(c4);
cl2.add(c5);
cl2.add(c6);
Tiberiu Leia: Software engineering Object management

51

cl1.add(c7);
cl1.add(c8);
System.out.println("Traveller List clasa 1 is:");
ListIterator iterator=cl1.listIterator();
while(iterator.hasNext())
{
Calator cal=(Calator)iterator.next();
System.out.println(cal);
}
System.out.println("Traveller List clasa 2 is:");
ListIterator iterator2=cl2.listIterator();
while(iterator2.hasNext())
{
Calator cal=(Calator)iterator2.next();
System.out.println(cal);
}
ArrayList join=new ArrayList();
join.addAll(cl1);
join.addAll(cl2);
ListIterator iterator3=join.listIterator();
Tiberiu Leia: Software engineering Object management

52

System.out.println("Lista reunita este:");


while(iterator3.hasNext())
{
Calator cal=(Calator)iterator3.next();
System.out.println(cal);
}
//Ordoneaza lista
Comparare comp=new Comparare();
Collections.sort(join,comp);
ListIterator iterator4=join.listIterator();
System.out.println("Lista ordonata este:");
while(iterator4.hasNext())
{
Calator cal=(Calator)iterator4.next();
System.out.println(cal);
}
} }

Draw the class diagram of the previous program!


Tiberiu Leia: Software engineering Object management

53

Calator

Comparator <<interface>>

+varsta: int
+sex: char
+cls: int

+compare(): int
+equals(): boolean

+toString(): String
*
Comparare
+rez: int
+temp1: int
+temp2: int

MainClass
+ci: Calator
+cl1: ArrayList
+cl2: ArrayList

+compare(): int
+equals(): boolean

+main()
How is that performed?

2
ArrayList
+add(Object)
+addAll(Collection)

Tiberiu Leia: Software engineering Object management

Collections
+sort(List, Comparator)

54

2. 3. Data Structures Mappings


refHashtable
Cheie Key
refObiectCheie
obiect1:Class1

Tiberiu Leia: Software engineering Object management

Valoare - Value
refObiectValoare
obiect2:Class2

55

Class Hashtable are constructorii:

Hashtable() - construiete o tabel (vid) cu capacitatea implicit


Hashtable(int) - idem cu capacitatea iniial precizat
Hashtable(float) - idem cu capacitatea iniial precizat mpreun cu un factor
de ncrcare.
Sunt implementate urmtoarele metode:
clear() - terge coninutul tabelei
clone() - creeaz o copie
contains(Object) - returneaz valoarea logic true dac obiectul este coninut
n tabel
containsKey(Object) - returneaz valoarea logic true dac obiectul este o
cheie n tabel
elements() - returneaz o enumerare a elementelor
keys() - returneaz o enumerare a cheilor din tabel
get(Object) - returneaz valoarea la care este aplicat n tabel cheia
specificat
put(Object, Object) - aplic cheia specificat la valoarea precizat n tabel
Tiberiu Leia: Software engineering Object management

56

rehash() - pune coninutul tabelei ntr-o tabel cu capacitatea mai mare


remove(Object) - elimin un obiect din tabel i returneaz valoarea la care a
fost mapat cheia
size() - returneaz numrul de chei din tabel
toString()

Tiberiu Leia: Software engineering Object management

57

Utilizare:
se creeaz obiectele
se creeaz tabelul Hashtable
se introduc in Hashtable
se efectueaz cutri ale obiectelor in tabel
se listeaz tot tabelul

Homework: Draw the class diagram of the previous program!

Modify the next program to correspond to the


proposed class diagram.

Tiberiu Leia: Software engineering Object management

58

Ex.:
//clasa pentru construirea unui obiect cu
nume si adresa
class NumeAdr {
String nume;
String adr;
NumeAdr(String numeAbon, String adrAbon) {
nume=new String(numeAbon);
adr=new String(adrAbon);
}
public String toString() {
return (nume+"; adresa="+adresa);
}
}
Tiberiu Leia: Software engineering Object management

59

public class NumeNrTelefon


{
public static void main (String[] args)
{
String abonat,adresa;
Hashtable tabH=new Hashtable();//creeaza tabela
Hash
//depune elemente in tabela
tabH.put("064-12345", new NumeAdr("Nume1
Prenume1", "Strada1 Nr.1"));
tabH.put("064-23456", new NumeAdr("Nume2
Prenume2", "Strada2 Nr.2"));
tabH.put("064-34567", new NumeAdr("Nume3
Prenume3","Strada3 Nr.3"));
//preia un element din tabela
NumeAdr na=(NumeAdr) tabH.get("064-12345");
abonat=new String(na.nume);
Tiberiu Leia: Software engineering Object management

60

adresa=new String(na.adr);
System.out.println("\nPersoana cu numarul 06412345 este:" +abonat);
System.out.println("Locuieste la dresa"+adresa);
na=(NumeAdr) tabH.get("064-34567");
abonat=new String(na.nume);
adresa=new String(na.adr);
System.out.println("\nPersoana cu numarul 06434567 este:" +abonat);
System.out.println("Locuieste la dresa"+adresa);
//enumereaza toate elementele din tabela
System.out.println("\nTabel cu persoanele
cuprinse in tabela:");
Enumeration en;
for(en=tabH.elements();en.hasMoreElements();)
System.out.println(
Tiberiu Leia: Software engineering Object management

61

((NumeAdr)en.nextElement()).nume);
}
}

Tiberiu Leia: Software engineering Object management

62

NumeNrTelefon
+tabH: Hashtable
+main(): void

Hashtable
+put()
+get(): Object

1..*
NumeAdr
+abonat: String
+adresa: String
+toString(): String

Tiberiu Leia: Software engineering Object management

<<Interface>>
Enumeration
+elements(): Object
+hasMoreElements(): boolean
+nextElement(): Object

63

Class HashMap
Implementeaz interfaa Map().Aceast interfa are definite metodele:
put(Object key, Object value) - depune o pereche cheie-valoare
get(Object key) - furnizeaz obiectul aflat n poziia dat de cheie
containsKey() - returneaz true dac exist cheia n HashMap
containsValue() - returneaz true dac exist valoarea respectiv n HashMap
clear()
clone();
entrySet()
putAll()
remove()
size()

Tiberiu Leia: Software engineering Object management

64

*
****
***END***
****
*
Tiberiu Leia: Software engineering Object management

65

Вам также может понравиться