JAVA 09

background image

Programo

w

anie

obiekto

w

e

(Ja

v

a)

9

1

T

yp

y

sparametryzo

w

ane

(ang.

generis)

"T

yp

y

sparametryzo

w

ane

[1℄

bardzo

w

a»ne

p

oniew

umo»liwia

t

w

orzenie

klas,

in

terfejsó

w

i

meto

d,

w

który

h

t

yp

obsªugiw

an

y

h

przez

nie

dan

y

h

jest

p

o

da

w

an

y

jak

o

parametr.

Inn

ymi

sªo

wy

,

programista

mo»e

op

ero

w

jedn¡

klas¡,

która

automat

yznie

b

dzie

op

ero

w

na

ró»n

y

h

t

ypa

h

dan

y

h.

Klas,

in

terfejs

lub

meto

d

k

orzysta

j¡¡

z

t

yp

ó

w

sparametryzo

w

an

y

h

nazyw

a

si

o

dp

o

wiednio

klas¡

sparametryzo

w

an¡,

in

terfejsem

sparametryzo

w

an

ym

lub

meto

sparametryzo

w

an¡."

1

publi

lass

Holder <E>

{

2

private

E

e;

3

4

publi

Holder

(E

e )

{

5

this

.e

=

e;

6

}

7

8

publi

E

get()

{

9

return

e;

10

}

11

12

publi

void

set (E

e)

{

13

this

.e

=

e;

14

}

15

16

Override

17

publi

int

hashCode

(){

18

return

e.hashCode

();

19

}

20

21

/*

publi

long

longValue

() {

22

return

e.longValue

() ;

ERROR

23

}*/

24

25

publi

stati

void

main (String [℄

args )

{

26

Holder < Integer >

i

=

new

Holder

<Integer >(

new

Integer (1) );

27

System . out.println

(i. get() );

28

}

29

}

Przykªad

1:

sr/pl/kiele/tu/lab9/Holder.ja

v

a

{link}

Jak

o

parametr

t

ypu

mo»na

wyk

orzyst

yw

t

ylk

o

klasy

.

Niedozw

olone

jest

u»yie

t

yp

ó

w

prost

y

h,

np.

int.

Problem

ten

mo»na

rozwi¡za¢

p

oprzez

u»yie

klas

opak

o

wuj¡y

h,

taki

h

jak

np.

Inte

ger.

U»yie

Holder<E>

p

o

w

o

duje,

»e

nie

mo»em

y

uzysk

»adnej

do

datk

o

w

ej

informaji

o

parametrze

t

ypu

E

.

W

wyniku

tego

dla

e

mo»em

y

wyw

oªyw

t

ylk

o

meto

dy

z

klasy

Obje

t

(e.hashCo

de()

w

p

o

wy»szym

przykªadzie).

Natomiast

wyw

oªania

meto

d

z

inn

y

h

klas

zak

o«z¡

si

bªdem.

Zastoso

w

anie

HolderExtends<E

extends

Numb

er>

w

p

oni»szym

przykªadzie

p

o

w

o

duje,

»e

jak

o

E

b

dzie

mo»na

u»y¢

klas

Num

b

er

oraz

wszystkie

p

o

niej

dziedziz¡e

(np.

A

tomiIn

teger,

A

tomiLong,

BigDeimal,

BigIn

teger,

Byte,

Double,

Float,

In

teger,

Long,

Short).

1

publi

lass

HolderExtends

< E

extends

Number >

{

2

3

private

E

e;

4

5

publi

HolderExtends

(E

e)

{

6

this

.e

=

e;

7

}

8

1

background image

9

publi

E

get()

{

10

return

e;

11

}

12

13

publi

void

set (E

e)

{

14

this

.e

=

e;

15

}

16

17

Override

18

publi

int

hashCode

(){

19

return

e.hashCode

();

20

}

21

22

publi

long

longValue

() {

23

return

e.longValue

();

24

}

25

26

publi

stati

void

main (String [℄

args )

{

27

HolderExtends

<Integer

>

i

=

new

HolderExtends

<Integer >(

new

Integer (1) );

28

System . out.println

(i. get() );

29

}

30

}

Przykªad

2:

sr/pl/kiele/tu/lab9/HolderExtends.ja

v

a

{link}

T

yp

y

parametryzo

w

ane

[5

niezmiennize.

W

p

oni»szym

przykªadzie

klasa

CCC

dziedzizy

p

o

BBB,

która

z

k

olei

dziedzizy

p

o

AAA.

Niezmiennizo±¢

t

yp

ó

w

parametryzo

w

an

y

h

oznaza,

»e

ta

hierar

hia

klas

nie

przenosi

si

na

Generi<AAA>,

Generi<BBB>

i

Generi<CCC> :

Generi<CCC>

nie

dziedzizy

p

o

Generi<BBB>,

p

o

dobnie

Generi<BBB>

nie

dziedzizy

p

o

Generi<AAA>.

1

publi

lass

TestGeneris

{

2

3

stati

lass

AAA

{

4

}

5

6

stati

lass

BBB

extends

AAA

{

7

}

8

9

stati

lass

CCC

extends

BBB

{

10

}

11

12

stati

lass

Generi <E >

{

13

}

14

15

publi

stati

void

main (String [℄

args )

{

16

Generi

<BBB>

b

=

new

Generi <BBB >() ;

17

Generi

<AAA>

a

=

new

Generi <AAA >() ;

18

//

b

=

a;

//

ERROR

19

Generi

<CCC>

=

new

Generi <CCC >() ;

20

//

b

=

;

//

ERROR

21

}

22

}

Przykªad

3:

sr/pl/kiele/tu/lab9/T

estGeneris.ja

v

a

{link}

2

Ogranizenia

Argumen

t

wieloznazn

y

[1℄

"T

aki

argumen

t

reprezen

tuje

nieznan

y

t

yp

i

oznaza

si

go

znakiem

zap

yta-

nia

(?

)."

"Ab

y

ustano

wi¢

górne

ogranizenie

wieloznazno±i

[1℄,

nale»y

za

wsze

k

orzysta¢

z

nastpuj¡ej

ogólnej

p

ostai

argumen

tu

wieloznaznego.

2

background image

<?

extends

klasa -bazowa

>

Elemen

t

klasa-bazo

w

a

to

nazw

a

klasy

,

stano

wi¡ej

ogranizenie

górne.

P

amita

j,

p

o

dana

klasa

tak»e

za

wiera

si

w

ogranizeniu,

zyli

mo»e

zosta¢

u»yta

jak

o

argumen

t."

"Ab

y

ustano

wi¢

dolne

ogranizenie

wieloznazno±i

[1

℄,

u»yw

a

si

klauzuli

sup

er

w

deklaraji

wieloznaz-

no±i.

Oto

górna

p

osta¢

takiego

rozwi¡zania.

<?

super

podklasa >

W

t

ym

przypadku

jak

o

argumen

t

dopuszzalne

t

ylk

o

te

klasy

,

które

zna

jduj¡

si

wy»ej

w

hierar

hii

dzie-

dzizenia

ni»

p

o

dklasa.

Inn

ymi

sªo

wy

,

jak

o

argumen

tu

nie

mo»na

przek

aza¢

klasy

p

o

dklasa

ani

»adnej

z

jej

klas

p

o

ho

dn

y

h."

P

oni»szy

przykªad

oprao

w

ano

na

p

o

ho

dzi

z:

Blo

h

Josh

ua,

Ja

v

a.

Efekt

ywne

programo

w

anie.

W

ydanie

I

I,

Helion,

2009

Dla

Stak<Numb

er>

numb

erStak

meto

da

push(E

e)

umo»liwia

do

da

w

ania

obiektó

w

klasy

Numb

er

oraz

jej

klas

p

o

ho

dn

y

h,

np.

Inte

ger.

Zaªó»m

y

,

»e

meto

da

pushA

l

l(Col

le

tion<E>

sr

)

ma

p

osiada¢

ta-

k

¡

sam¡

funk

jonalno±¢,

ale

dla

k

olek

ji

obiektó

w.

W

yw

oªanie

meto

dy

z

argumen

tem

Col

le

tion<Numb

er>

jest

mo»liw

e,

natomiast

dla

argumen

tu

Col

le

tion<Inte

ger>

wystpuje

bª¡d

k

ompilaji.

Zastoso

w

anie

pu-

shA

l

l(Col

le

tion<?

extends

E>

sr

)

w

klasie

StakSup

erExtends<E>

p

o

w

o

duje

usuniie

tego

bªdu,

przy

jedno

zesn

ym

za

ho

w

aniu

k

on

troli

t

yp

ó

w.

Dla

Stak<Numb

er>

numb

erStak

meto

da

p

op()

umo»liwia

p

obieranie

obiektó

w

i

przypisanie

i

h

do

refe-

renji

Numb

er

oraz

jej

klas

bazo

wy

h,

np.

Obje

t.

Zaªó»m

y

,

»e

meto

da

p

opA

l

l(Col

le

tion<E>

dst)

ma

p

osiada¢

tak

¡

sam¡

funk

jonalno±¢,

ale

dla

k

olek

ji

obiektó

w.

W

yw

oªanie

meto

dy

z

argumen

tem

Col

le

tion<Numb

er>

jest

mo»liw

e,

natomiast

dla

argumen

tu

Col

le

tion<Inte

ger>

wystpuje

bª¡d

k

ompilaji.

Zastoso

w

anie

p

o-

pA

l

l(Col

le

tion<?

sup

er

E>

dst)

w

klasie

StakSup

erExtends<E>

p

o

w

o

duje

usuniie

tego

bªdu,

przy

jed-

no

zesn

ym

za

ho

w

aniu

k

on

troli

t

yp

ó

w.

Opisane

p

o

wy»ej

rozwi¡zanie

jest

zgo

dne

z

zasad¡

PECS

[5

℄.

Jej

nazw

a

p

o

ho

dzi

o

d

pierwszy

h

liter

angielski

h

sªó

w

pro

duerextends,

onsumersup

er.

1

publi

lass

Stak <E>

{

2

publi

Stak ()

{

3

//

...

4

}

5

6

publi

void

push ( E

e)

{

7

//

...

8

}

9

10

publi

void

pushAll

(Colletion

< E>

sr )

{

11

for

(E

e

:

sr )

12

push (e );

13

}

14

15

publi

E

pop()

{

16

E

e

=

null

;

17

//

...

18

return

e;

19

}

20

21

publi

void

popAll

(Colletion

<E >

dst )

{

22

while

(!

isEmpty () )

23

dst .add (pop ());

24

}

25

26

publi

boolean

isEmpty

()

{

27

boolean

empty

=

false

;

28

//

...

29

return

empty ;

30

}

3

background image

31

32

publi

stati

void

main (String [℄

args )

{

33

Stak <Number

>

numberStak

=

new

Stak <Number

>();

34

numberStak

. push (

new

Integer (1) );

35

Objet

o

=

numberStak

.pop ();

36

37

Colletion

<Number

>

numberColletion

=

new

HashSet

<Number >() ;

38

numberStak

. pushAll (numberColletion

);

39

numberStak

. popAll (numberColletion

);

40

41

Colletion

<Integer

>

integerColletion

=

new

HashSet <Integer

>() ;

42

//

atual

argument

Colletion

< Integer >

annot

be

onverted

to

Colletion

<Number >

by

←֓

method

invoation

onversion

43

//

numberStak

.pushAll

(integerColletion

);

44

45

Colletion

<Objet

>

objetColletion

=

new

HashSet

<Objet >() ;

46

//

atual

argument

Colletion

< Objet >

annot

be

onverted

to

Colletion

<Number >

by

method

←֓

invoation

onversion

47

//

numberStak

.popAll

(objetColletion

) ;

48

}

49

}

Przykªad

4:

sr/pl/kiele/tu/lab9/Sta

k.ja

v

a

{link}

1

publi

lass

StakSuperExtends

<E >

{

2

publi

StakSuperExtends

()

{

3

//

...

4

}

5

6

publi

void

push ( E

e)

{

7

//

...

8

}

9

10

publi

void

pushAll

(Colletion

<?

extends

E>

sr )

{

11

for

(E

e

:

sr )

12

push (e );

13

}

14

15

publi

E

pop()

{

16

E

e

=

null

;

17

//

...

18

return

e;

19

}

20

21

publi

void

popAll

(Colletion

<?

super

E>

dst)

{

22

while

(!

isEmpty () )

23

dst .add (pop ());

24

}

25

26

publi

boolean

isEmpty

()

{

27

boolean

empty

=

false

;

28

//

...

29

return

empty ;

30

}

31

32

publi

stati

void

main (String [℄

args )

{

33

StakSuperExtends

<Number >

numberStak

=

new

StakSuperExtends

< Number >() ;

34

numberStak

. push (

new

Integer (1) );

35

Objet

o

=

numberStak

.pop ();

36

37

Colletion

<Number

>

numberColletion

=

new

HashSet

<Number >() ;

4

background image

38

numberStak

. pushAll (numberColletion

);

39

numberStak

. popAll (numberColletion

);

40

41

Colletion

<Integer

>

integerStak

=

new

HashSet <Integer

>();

42

numberStak

. pushAll (integerStak

);

43

44

Colletion

<Objet

>

objetStak

=

new

HashSet

<Objet >() ;

45

numberStak

. popAll (objetStak

);

46

}

47

}

Przykªad

5:

sr/pl/kiele/tu/lab9/Sta

kSup

erExtends.ja

v

a

{link}

3

Meto

dy

sparametryzo

w

ane

P

arametryzaja

mo»e

zosta¢

wyk

orzystana

w

stosunku

do

klas,

in

terfejsó

w,

meto

d,

a

na

w

et

k

onstruktoró

w.

1

publi

lass

GeneriMethods

{

2

publi

stati

<T

extends

Comparable

<T>>

T

min (T

t1 ,

T

t2)

{

3

if

(t1. ompareTo

(t2)

<

0)

4

return

t1;

5

else

6

return

t2;

7

}

8

publi

stati

<T

extends

Comparable

<T>>

T

max (T

t1 ,

T

t2)

{

9

if

(t1. ompareTo

(t2)

>

0)

10

return

t1;

11

else

12

return

t2;

13

}

14

publi

stati

<T

extends

Comparable

<T>>

boolean

equal ( T

t1 ,

T

t2 )

{

15

if

(t1. ompareTo

(t2)

==

0)

16

return

true

;

17

else

18

return

false

;

19

}

20

publi

stati

void

main (String [℄

args )

{

21

Integer

i1

=

1;

22

Integer

i2

=

2;

23

if

(equal (i1 ,

i2 ))

24

System

.out. println (i1

+

"

equal

"

+

i2 );

25

else

{

26

if

(i1 .equals (min (i1 ,

i2) ))

27

System

.out .println ( i1

+

"

is

less

than

"

+

i2);

28

else

29

System

.out .println ( i2

+

"

is

less

than

"

+

i1);

30

}

31

}

32

}

Przykªad

6:

sr/pl/kiele/tu/lab9/GeneriMetho

ds.ja

v

a

{link}

4

K

olek

je

K

olek

ja

Colletion

[2

℄:

grupa

o

drbn

y

h

elemen

w,

p

o

dlega

j¡y

h

jakim±

reguªom.

Na

przykªad

List

m

usi

prze

ho

wyw

elemen

t

y

w

okre±lonej

k

olejno±i,

zbiór

Set

nie

mo»e

za

wiera¢

duplik

ató

w,

a

k

olejk

a

Queue

p

orz¡dkuje

elemen

t

y

w

edªug

dysyplin

y

k

olejki

(zwykle

p

ostuluje

ona

k

olejno±¢

iden

t

yzn¡

z

k

olejno±i¡

wsta

wiania

elemen

w).

5

background image

Odwzoro

w

anie

Map:

1

grupa

para

obiektó

w

t

ypu

kluz

w

arto±¢,

p

ozw

ala

j¡a

na

wydob

yw

anie

w

arto±i

dla

znanego

kluza

.

K

on

tenery

<

Ja

v

a

1.5

oraz

k

on

tenery

>

=

Ja

v

a

1.5

1

publi

lass

TestContainers1

{

2

stati

lass

Dog

{

3

}

4

5

stati

lass

Cat

{

6

}

7

publi

stati

void

main (String [℄

args )

{

8

HashSet

dogs

=

new

HashSet

();

9

dogs .add (

new

Dog ());

10

dogs .add (

new

Cat ());

11

Iterator

i

=

dogs .iterator

();

12

while

( i.hasNext

())

{

13

Dog

d

=

(Dog )

i .next ();

14

//

java .lang .ClassCastExeption

:

Cat

annot

be

ast

to

Dog

15

System

.out. println (d );

16

}

17

}

18

}

Przykªad

7:

sr/pl/kiele/tu/lab9/T

estCon

tainers1.ja

v

a

{link}

1

publi

lass

TestContainers2

{

2

stati

lass

Dog

{

3

}

4

5

stati

lass

Cat

{

6

}

7

8

publi

stati

void

main (String [℄

args )

{

9

HashSet

<Dog>

dogs

=

new

HashSet

<Dog >();

10

dogs .add (

new

Dog ());

11

//

The

method

add (Dog )

is

not

appliable

for

argument

Cat

12

//

dogs .add( new

Cat() );

13

for

(Dog

d

:

dogs )

14

System

.out. println (d );

15

}

16

}

Przykªad

8:

sr/pl/kiele/tu/lab9/T

estCon

tainers2.ja

v

a

{link}

5

P

o

dsta

w

o

w

e

me

hanizm

y

dziaªania

k

olek

ji

P

oni»ej

przedsta

wiono

uproszzone

implemen

taje

k

olek

ji

wyk

orzystuj¡e

nastpuj¡e

me

hanizm

y:

ˆ

tablia

MyA

rr

ayCol

le

tion,

ˆ

lista

MyLinke

dCol

le

tion,

ˆ

funk

ja

haszuj¡a

(miesza

j¡a)

MyHashCol

le

tion,

ˆ

drzew

o

binarne

MyT

r

e

eCol

le

tion.

Przedsta

wione

implemen

taje

ma

t

ylk

o

harakter

p

ogl¡do

wy

i

niek

onieznie

zgo

dn

y

z

zastoso

w

an

ymi

w

bibliotee

standardo

w

ej

Ja

vy

.

1

publi

lass

MyArrayColletion

<E >

{

6

background image

2

3

private

E[℄

objets

;

4

private

int

index

;

5

6

publi

MyArrayColletion

(

int

initialCapaity

)

{

7

objets

=

(E [℄)

new

Objet

[initialCapaity

℄;

8

}

9

10

publi

boolean

add (E

newObj

)

{

11

//

not

empty

spae

12

if

(index

>=

objets . length )

13

return

false

;

14

15

objets

[index ++℄

=

newObj

;

16

return

true

;

17

}

18

19

publi

boolean

delete ( E

obj )

{

20

for

(

int

i

=

0;

i

<=

index ;

i++)

{

21

//

founded

22

if

(objets

[i℄. equals (obj ))

{

23

//

move

other

objets

24

System

.arrayopy

(objets

,

i

+

1,

objets ,

i,

index

-

i

-

1);

25

26

//

null

the

last

one

27

objets

[objets

.length

-

1℄

=

null

;

28

29

//

atualize

index

30

-- index ;

31

return

true

;

32

}

33

}

34

//

not

founded

35

return

false

;

36

}

37

38

Override

39

publi

String

toString

()

{

40

String

answer

=

"["

;

41

for

(

int

i

=

0;

i

<

index

;

i++)

{

42

answer

+=

objets

[i℄;

43

if

(i

!=

index

-

1)

44

answer

+=

",

"

;

45

}

46

answer

+=

"℄ "

;

47

return

answer ;

48

}

49

}

Przykªad

9:

sr/pl/kiele/tu/lab9/MyArra

yColletio

n.ja

v

a

{link}

1

publi

lass

MyLinkedColletion

< E>

{

2

3

private

Node< E>

head ;

4

private

Node< E>

tail ;

5

6

publi

boolean

add (E

newObj

)

{

7

if

(tail

==

null

)

{

8

tail

=

new

Node <E>(newObj

);

9

head

=

tail ;

10

return

true

;

7

background image

11

}

12

13

tail .next

=

new

Node< E>(newObj

);

14

tail

=

tail. next ;

15

return

true

;

16

}

17

18

publi

boolean

delete ( E

obj )

{

19

//

empty

list

20

if

(head

==

null

)

21

return

false

;

22

23

//

hek

head

24

if

(head .obj .equals (obj ))

{

25

//

only

one

element

(head

==

tail)

26

if

(tail

==

head )

27

tail

=

head .next ;

//

null

28

//

move

to

the

next

one

29

head

=

head .next ;

30

return

true

;

31

}

32

33

Node <E>

tmp

=

head ;

34

while

( tmp.next

!=

null

)

{

35

if

(tmp .next .obj .equals (obj ))

{

36

//

atualize

tail

37

if

(tail

==

tmp .next )

38

tail

=

tmp ;

39

//

remove

40

tmp .next

=

tmp. next .next ;

41

return

true

;

42

}

43

//

move

to

the

next

one

44

tmp

=

tmp.next ;

45

}

46

return

false

;

47

}

48

49

Override

50

publi

String

toString

()

{

51

String

answer

=

"["

;

52

Node <E>

tmp

=

head ;

53

while

( tmp

!=

null

)

{

54

answer

+=

tmp .obj ;

55

if

(tmp .next

!=

null

)

56

answer

+=

",

"

;

57

tmp

=

tmp.next ;

58

}

59

answer

+=

"℄ "

;

60

answer

+=

"

head

=

"

+

(head

==

null

?

null

:

head .obj )

+

",

tail

=

"

61

+

(tail

==

null

?

null

:

tail .obj );

62

return

answer ;

63

}

64

65

private

lass

Node <F>

{

66

private

F

obj ;

67

private

Node <F>

next;

68

69

private

Node (F

obj )

{

70

this

.obj

=

obj;

71

}

72

}

8

background image

73

}

Przykªad

10:

sr/pl/kiele/tu/lab9/MyLink

edColletion.ja

v

a

{link}

1

publi

lass

MyHashColletion

<E>

{

2

3

private

MyBuket < E>[℄

bukets ;

4

private

int

buketsQuantity

;

5

6

publi

MyHashColletion

(

int

buketsQuantity

,

int

buketCapaity

)

{

7

this

.buketsQuantity

=

buketsQuantity

;

8

this

.bukets

=

( MyBuket < E>[℄)

new

MyBuket

[buketsQuantity

℄;

9

for

(

int

i

=

0;

i

<

buketsQuantity

;

i++)

10

this

.bukets

[i℄

=

new

MyBuket

<E>( buketCapaity

);

11

}

12

13

/**

14

*

Adds

the

objet

only

when

it

does

not

exists

in

the

olletion

15

*

param

obj

the

objet

whih

should

be

added

16

*

return

true

if

the

objet

was

added ,

and

false

otherwise

17

*/

18

publi

boolean

add (E

obj )

{

19

int

hashCode

=

obj .hashCode

();

20

int

buketNumber

=

hashCode

%

buketsQuantity

;

21

return

bukets [buketNumber

℄.add (obj );

22

}

23

24

/**

25

*

Deletes

objet

from

the

olletion

26

*

param

obj

the

objet

whih

should

be

deleted

27

*

return

true

if

the

objet

was

deleted

,

and

false

otherwise

28

*/

29

publi

boolean

delete ( E

obj )

{

30

int

hashCode

=

obj .hashCode

();

31

int

buketNumber

=

hashCode

%

buketsQuantity

;

32

return

bukets [buketNumber

℄.delete

(obj );

33

}

34

35

Override

36

publi

String

toString

()

{

37

String

answer

=

"["

;

38

for

(

int

i

=

0;

i

<

bukets

.length ;

i++)

{

39

answer

+=

bukets

[i℄;

40

if

(i

!=

bukets

.length

-

1)

41

answer

+=

",

"

;

42

}

43

answer

+=

"℄ "

;

44

return

answer ;

45

}

46

47

private

lass

MyBuket

<F>

{

48

final

private

stati

int

NONE

=

-1;

49

private

F[℄

objets ;

50

51

publi

MyBuket (

int

buketCapaity

)

{

52

objets

=

( F[℄)

new

Objet

[buketCapaity

℄;

53

}

54

55

/**

56

*

Adds

the

objet

only

when

it

does

not

exists

in

the

buket

57

*

param

obj

the

objet

whih

should

be

added

9

background image

58

*

return

true

if

the

objet

was

added ,

and

false

otherwise

59

*/

60

publi

boolean

add (F

obj)

{

61

int

empty

=

NONE ;

62

63

for

(

int

i

=

0;

i

<

objets .length

;

i++)

{

64

//

heks

whether

there

is

an

empty

spae

65

if

(empty

==

NONE

&&

objets

[i℄

==

null

)

66

empty

=

i ;

67

68

//

heks

whether

the

objet

already

was

added

69

if

(objets

[i℄

!=

null

&&

objets

[i℄. equals (obj ))

70

return

false

;

71

}

72

//

not

empty

spae

73

if

(empty

==

NONE )

74

return

false

;

75

76

//

adds

objet

77

objets

[empty ℄

=

obj ;

78

return

true

;

79

}

80

81

/**

82

*

Deletes

objet

from

the

buket

83

*

param

obj

the

objet

whih

should

be

deleted

84

*

return

true

if

the

objet

was

deleted ,

and

false

otherwise

85

*/

86

publi

boolean

delete

(F

obj )

{

87

for

(

int

i

=

0;

i

<

objets .length

;

i++)

{

88

//

heks

whether

the

objet

was

added

89

if

(objets

[i℄

!=

null

&&

objets

[i℄. equals (obj ))

{

90

objets [i ℄

=

null

;

91

return

true

;

92

}

93

}

94

return

false

;

95

}

96

97

Override

98

publi

String

toString

()

{

Przykªad

11:

sr/pl/kiele/tu/lab9/MyHashColletion.ja

v

a

{link}

1

publi

lass

MyTreeColletion

<E>

{

2

private

final

stati

String

nl

=

System . getProperty

(

"line . separator "

);

3

4

private

Node< E>

root ;

5

6

publi

boolean

add (E

newObj

)

{

7

if

(root

==

null

)

{

8

root

=

new

Node <E>(newObj

);

9

return

true

;

10

}

11

Node <E>

tmpNode

=

root ;

12

E

tmpObjet

=

tmpNode

.obj ;

13

Comparable

<E >

tmpComparable

=

(Comparable

<E>) tmpObjet

;

14

int

result

=

0;

15

for

(;;)

{

16

result

=

tmpComparable

.ompareTo

(newObj

);

17

if

(result

==

0)

{

10

background image

18

//

the

obj

already

exists

19

return

false

;

20

}

21

if

(result

<

0)

{

22

//

left

23

if

(tmpNode

.left

==

null

)

{

24

//

add

25

tmpNode .left

=

new

Node <E>( newObj );

26

return

true

;

27

}

else

{

28

//

move

left

29

tmpNode

=

tmpNode . left;

30

tmpObjet

=

tmpNode

.obj ;

31

tmpComparable

=

(Comparable

<E>)

tmpObjet

;

32

}

33

}

else

{

34

//

right

35

if

(tmpNode

.right

==

null

)

{

36

//

add

37

tmpNode .right

=

new

Node <E>( newObj );

38

return

true

;

39

}

else

{

40

//

move

right

41

tmpNode

=

tmpNode . right ;

42

tmpObjet

=

tmpNode

.obj ;

43

tmpComparable

=

(Comparable

<E>)

tmpObjet

;

44

}

45

}

46

}

47

}

48

49

Override

50

publi

String

toString

()

{

51

String

value

=

" "

;

52

value

+=

print (root ,

0,

false

) ;

53

return

value ;

54

}

55

56

private

String

print (Node < E>

node ,

int

level ,

boolean

left )

{

57

String

value

=

println

(node ,

level ,

left );

58

if

(node

==

null

)

59

return

value ;

60

61

value

+=

print (node .left ,

level

+

1,

true

);

62

value

+=

print (node .right

,

level

+

1,

false

) ;

63

return

value ;

64

}

65

66

private

String

println

(Node <E>

node ,

int

level ,

boolean

left )

{

67

String

value

=

" "

;

68

for

(

int

i

=

0;

i

<

level

-

1;

i++)

69

value

+=

"

|

"

;

70

if

(level

>

0)

{

71

if

(left )

72

value

+=

" \\--"

+

( node

==

null

?

"*"

:

node .obj )

+

nl;

73

else

74

value

+=

" \\=="

+

( node

==

null

?

"*"

:

node .obj )

+

nl;

75

}

else

76

value

+=

node .obj

+

nl;

77

return

value ;

78

}

79

11

background image

80

private

lass

Node <F>

{

81

private

F

obj ;

82

private

Node <F>

left,

right ;

83

84

private

Node (F

obj )

{

85

this

.obj

=

obj;

86

}

87

}

88

}

Przykªad

12:

sr/pl/kiele/tu/lab9/MyT

reeColletion.ja

v

a

{link}

6

Bibliotek

a

standardo

w

a

6.1

In

terfejsy

In

terfejsy

zwi¡zane

z

k

olek

jami

1

:

ˆ

java.util.Col

le

tion,

który

rozszerza

in

terfejsy:

java.util.Set,

java.util.Sorte

dSet,

java.util.NavigableSet,

java.util.Queue,

java.util.

onurr

ent.Blo

kingQueue,

java.util.

onurr

ent.T

r

ansferQueue,

java.util.De

que,

java.util.

onurr

ent.Blo

kingDe

que,

ˆ

java.util.Map,

który

rozszerza

in

terfejsy:

java.util.Sorte

dMap,

java.util.NavigableMap,

java.util.

onurr

ent.Conurr

entMap,

java.util.

onurr

ent.Conurr

entNavigableMap.

6.2

Colletion<E>

In

terfejs

Col

le

tion<E>

extends

Iter

able<E> :

ˆ

b

o

ole

an

add(E

e),

ˆ

b

o

ole

an

addA

l

l(Col

le

tion<?

extends

E>

),

ˆ

void

le

ar(),

ˆ

b

o

ole

an

ontains(Obje

t

o),

ˆ

b

o

ole

an

ontainsA

l

l(Col

le

tion<?>

),

ˆ

b

o

ole

an

e

quals(Obje

t

o),

ˆ

int

hashCo

de(),

ˆ

b

o

ole

an

isEmpty(),

ˆ

Iter

ator<E>

iter

ator(),

1

h

ttp://do

s.orale.om/ja

v

ase/7/do

s/te

hnot es/gu ides/ollet ions/o

v

erv iew.h

tml

12

background image

ˆ

b

o

ole

an

r

emove(Obje

t

o),

ˆ

b

o

ole

an

r

emoveA

l

l(Col

le

tion<?>

),

ˆ

b

o

ole

an

r

etainA

l

l(Col

le

tion<?>

),

ˆ

int

size(),

ˆ

Obje

t[℄

toA

rr

ay(),

ˆ

<T>

T[℄

toA

rr

ay(T[℄

a).

6.2.1

Iterable<T>

In

terfejs

Iter

able<T> :

ˆ

Iter

ator<T>

iter

ator().

6.2.2

Iterator<T>

In

terfejs

Iter

ator<T> :

ˆ

b

o

ole

an

hasNext(),

ˆ

E

next(),

ˆ

void

r

emove().

6.3

In

terfejs

Set<E>

In

terfejs

Set<E>

extends

Col

le

tion<E>

za

wiera

takie

same

meto

dy

jak

in

terfejs

Col

le

tion<E>.

6.3.1

In

terfejs

SortedSet<E>

In

terfejs

Sorte

dSet<E>

extends

Set<E> :

ˆ

Comp

ar

ator<?

sup

er

E>

omp

ar

ator(),

ˆ

E

rst(),

ˆ

Sorte

dSet<E>

he

adSet(E

toElement),

ˆ

E

last(),

ˆ

Sorte

dSet<E>

subSet(E

fr

omElement,

E

toElement),

ˆ

Sorte

dSet<E>

tailSet(E

fr

omElement),

ˆ

p

ozostaªe

meto

dy

zadeklaro

w

ane

w

in

terfejsie

Set<E>.

6.3.2

In

terfejs

Na

vigableSet<E>

In

terfejs

publi

interfa

e

NavigableSet<E>

extends

Sorte

dSet<E> :

ˆ

E

eiling(E

e),

ˆ

Iter

ator<E>

des

endingIter

ator(),

ˆ

NavigableSet<E>

des

endingSet(),

ˆ

E

o

or(E

e),

ˆ

Sorte

dSet<E>

he

adSet(E

toElement),

ˆ

NavigableSet<E>

he

adSet(E

toElement,

b

o

ole

an

inlusive),

13

background image

ˆ

E

higher(E

e),

ˆ

E

lower(E

e),

ˆ

E

p

ol

lFirst(),

ˆ

E

p

ol

lL

ast(),

ˆ

NavigableSet<E>

subSet(E

fr

omElement,

b

o

ole

an

fr

omInlusive,

E

toElement,

b

o

ole

an

toInlusive),

ˆ

Sorte

dSet<E>

subSet(E

fr

omElement,

E

toElement),

ˆ

Sorte

dSet<E>

tailSet(E

fr

omElement),

ˆ

NavigableSet<E>

tailSet(E

fr

omElement,

b

o

ole

an

inlusive),

ˆ

p

ozostaªe

meto

dy

zadeklaro

w

ane

w

in

terfejsie

Sorte

dSet<E>.

6.4

In

terfejs

List<E>

In

terfejs

List<E>

extends

Col

le

tion<E> :

ˆ

void

add(int

index,

E

element),

ˆ

b

o

ole

an

addA

l

l(int

index,

Col

le

tion<?

extends

E>

),

ˆ

E

get(int

index),

ˆ

int

indexOf(Obje

t

o),

ˆ

int

lastIndexOf(Obje

t

o),

ˆ

ListIter

ator<E>

listIter

ator(),

ˆ

ListIter

ator<E>

listIter

ator(int

index),

ˆ

E

r

emove(int

index),

ˆ

E

set(int

index,

E

element),

ˆ

List<E>

subList(int

fr

omIndex,

int

toIndex),

ˆ

p

ozostaªe

meto

dy

zadeklaro

w

ane

w

in

terfejsie

Col

le

tion<E>.

6.5

In

terfejs

Queue<E>

In

terfejs

Queue<E>

extends

Col

le

tion<E>

rozszerza

in

terfejs

Col

le

tion<E>

o

meto

dy

sªu»¡e

do

do-

da

w

ania,

usu

w

ania

i

p

obierania

obiektó

w.

Meto

dy

te

istniej¡

w

dw

ó

h

w

arian

ta

h:

zgªasza

j¡ym

wyj¡tek

gdy

op

eraja

si

nie

p

o

wiedzie

lub

zwraa

j¡ym

sp

ejaln¡

w

arto±¢

(nul

l

lub

false

)

2

:

Thr

ows

ex

eption

R

eturns

sp

e

ial

value

Insert

add(e)

oer(e)

Remo

v

e

remo

v

e()

p

oll()

Examine

elemen

t()

p

eek()

In

terfejs

Queue<E>

extends

Col

le

tion<E> :

ˆ

b

o

ole

an

add(E

e),

ˆ

E

element(),

ˆ

b

o

ole

an

oer(E

e),

ˆ

E

p

e

ek(),

2

h

ttp://do

s.orale.om/ja

v

ase/7/do

s/api/ja

v

a/ut il/Queue.h

tml

14

background image

ˆ

E

p

ol

l(),

ˆ

E

r

emove(),

ˆ

p

ozostaªe

meto

dy

zadeklaro

w

ane

w

in

terfejsie

Col

le

tion<E>.

6.6

In

terfejs

Deque<E>

In

terfejs

publi

interfa

e

De

que<E>

extends

Queue<E>

rozszerza

in

terfejs

Queue<E>

o

meto

dy

sªu»¡e

do

do

da

w

ania,

usu

w

ania

i

p

obierania

obiektó

w

z

obu

k

o«ó

w

k

olejki.

Meto

dy

te

istniej¡

w

dw

ó

h

w

arian

ta

h:

zgªasza

j¡ym

wyj¡tek

gdy

op

eraja

si

nie

p

o

wiedzie

lub

zwraa

j¡ym

sp

ejaln¡

w

arto±¢

(nul

l

lub

false

)

3

:

First

Elemen

t

(Head)

Last

Elemen

t

(T

ail)

Thr

ows

ex

eption

Sp

e

ial

value

Thr

ows

ex

eption

Sp

e

ial

value

Insert

addFirst(e)

oerFirst(e)

addLast(e)

oerLast(e)

Remo

v

e

remo

v

eFirst()

p

ollFirst()

remo

v

eLast()

p

ollLast()

Examine

getFirst()

p

eekFirst()

getLast()

p

eekLast()

Kiedy

k

olejk

a

dwukierunk

o

w

a

(deque)

jest

u»yw

ana

jak

o

jednokierunk

o

w

ej

(queue)

uzyskujem

y

za

ho

w

anie

zgo

dne

z

meto

FIF

O

(ang.

First-In-First-Out).

Lista

meto

d

o

dziedzizon

y

z

klasy

Queue

o

dp

o

wiada

j¡y

h

meto

dom

z

klasy

De

que

3

:

Queue

Metho

d

Equiv

alen

t

Deque

Metho

d

add(e)

addLast(e)

oer(e)

oerLast(e)

remo

v

e()

remo

v

eFirst()

p

oll()

p

ollFirst()

elemen

t()

getFirst()

p

eek()

p

eekFirst()

K

olejk

a

dwukierunk

o

w

a

(deque)

mo»e

b

tak»e

u»yta

jak

o

stos

zgo

dnie

z

meto

LIF

O

(ang.

Last-In-

First-Out)

3

:

Sta

k

Metho

d

Equiv

alen

t

Deque

Metho

d

push(e)

addFirst(e)

p

op()

remo

v

eFirst()

p

eek()

p

eekFirst()

In

terfejs

De

que<E>

extends

Queue<E> :

ˆ

void

addFirst(E

e),

ˆ

void

addL

ast(E

e),

ˆ

Iter

ator<E>

des

endingIter

ator(),

ˆ

E

getFirst(),

ˆ

E

getL

ast(),

ˆ

b

o

ole

an

oerFirst(E

e),

ˆ

b

o

ole

an

oerL

ast(E

e),

ˆ

E

p

e

ekFirst(),

ˆ

E

p

e

ekL

ast(),

ˆ

E

p

ol

lFirst(),

3

h

ttp://do

s.orale.om/ja

v

ase/7/do

s/api/ja

v

a/ut il/Deque.h

tml

15

background image

ˆ

E

p

ol

lL

ast(),

ˆ

E

p

op(),

ˆ

void

push(E

e),

ˆ

E

r

emoveFirst(),

ˆ

b

o

ole

an

r

emoveFirstO

urr

en

e(Obje

t

o),

ˆ

E

r

emoveL

ast(),

ˆ

b

o

ole

an

r

emoveL

astO

urr

en

e(Obje

t

o),

ˆ

p

ozostaªe

meto

dy

zadeklaro

w

ane

w

in

terfejsie

Queue<E>.

6.7

In

terfejs

Map<K,V>

In

terfejs

publi

interfa

e

Map<K,V> :

ˆ

void

le

ar(),

ˆ

b

o

ole

an

ontainsKey(Obje

t

key),

ˆ

b

o

ole

an

ontainsV

alue(Obje

t

value),

ˆ

Set<Map.Entry<K,V

entrySet(),

ˆ

b

o

ole

an

e

quals(Obje

t

o),

ˆ

V

get(Obje

t

key),

ˆ

int

hashCo

de(),

ˆ

b

o

ole

an

isEmpty(),

ˆ

Set<K>

keySet(),

ˆ

V

put(K

key,

V

value),

ˆ

void

putA

l

l(Map<?

extends

K,?

extends

V>

m),

ˆ

V

r

emove(Obje

t

key),

ˆ

int

size(),

ˆ

Col

le

tion<V>

values().

6.7.1

In

terfejs

SortedMap<K,V>

In

terfejs

Sorte

dMap<K,V>

extends

Map<K,V> :

ˆ

Comp

ar

ator<?

sup

er

K>

omp

ar

ator(),

ˆ

K

rstKey(),

ˆ

Sorte

dMap<K,V>

he

adMap(K

toKey),

ˆ

K

lastKey(),

ˆ

Sorte

dMap<K,V>

subMap(K

fr

omKey,

K

toKey),

ˆ

Sorte

dMap<K,V>

tailMap(K

fr

omKey),

ˆ

p

ozostaªe

meto

dy

zadeklaro

w

ane

w

in

terfejsie

Queue<E>.

16

background image

6.7.2

In

terfejs

Na

vigableMap<K,V>

In

terfejs

publi

interfa

e

NavigableMap<K,V>

extends

Sorte

dMap<K,V> :

ˆ

Map.Entry<K,V>

eilingEntry(K

key),

ˆ

K

eilingKey(K

key),

ˆ

NavigableSet<K>

des

endingKeySet(),

ˆ

NavigableMap<K,V>

des

endingMap(),

ˆ

Map.Entry<K,V>

rstEntry(),

ˆ

Map.Entry<K,V>

o

orEntry(K

key),

ˆ

K

o

orKey(K

key),

ˆ

NavigableMap<K,V>

he

adMap(K

toKey,

b

o

ole

an

inlusive),

ˆ

Map.Entry<K,V>

higherEntry(K

key),

ˆ

K

higherKey(K

key),

ˆ

Map.Entry<K,V>

lastEntry(),

ˆ

Map.Entry<K,V>

lowerEntry(K

key),

ˆ

K

lowerKey(K

key),

ˆ

NavigableSet<K>

navigableKeySet(),

ˆ

Map.Entry<K,V>

p

ol

lFirstEntry(),

ˆ

Map.Entry<K,V>

p

ol

lL

astEntry(),

ˆ

NavigableMap<K,V>

subMap(K

fr

omKey,

b

o

ole

an

fr

omInlusive,

K

toKey,

b

o

ole

an

toInlusive),

ˆ

NavigableMap<K,V>

tailMap(K

fr

omKey,

b

o

ole

an

inlusive),

ˆ

p

ozostaªe

meto

dy

zadeklaro

w

ane

w

in

terfejsie

Sorte

dMap<E>.

6.7.3

In

terfejs

Map.En

try<K,V>

In

terfejs

Map.Entry<K,V> :

ˆ

b

o

ole

an

e

quals(Obje

t

o),

ˆ

K

getKey(),

ˆ

V

getV

alue(),

ˆ

int

hashCo

de(),

ˆ

V

setV

alue(V

value).

6.8

P

oró

wn

yw

anie

6.8.1

In

terfejs

Comparable<T>

In

terfejs

Comp

ar

able<T> :

ˆ

int

omp

ar

eT

o(T

o).

17

background image

6.8.2

In

terfejs

Comparator<T>

In

terfejs

Comp

ar

ator<T> :

ˆ

int

omp

ar

e(T

o1,

T

o2),

ˆ

b

o

ole

an

e

quals(Obje

t

obj).

6.9

Klasy

abstrak

yjne

Klasy

abstrak

yjne

zwi¡zane

z

k

olek

jami

1

:

ˆ

publi

abstr

at

lass

A

bstr

atCol

le

tion<E>

extends

Obje

t

implements

Col

le

tion<E>,

ˆ

publi

abstr

at

lass

A

bstr

atSet<E>

extends

A

bstr

atCol

le

tion<E>

implements

Set<E>,

ˆ

publi

abstr

at

lass

A

bstr

atList<E>

extends

A

bstr

atCol

le

tion<E>

implements

List<E>,

ˆ

publi

abstr

at

lass

A

bstr

atSe

quentialList<E>

extends

A

bstr

atList<E>,

ˆ

publi

abstr

at

lass

A

bstr

atMap<K,V>

extends

Obje

t

implements

Map<K,V>.

6.10

Klasy

k

onkretne

Implemen

taje

k

olek

ji

1

:

In

terfae

Hash

T

able

Resizable

Arra

y

Balaned

T

ree

Link

ed

List

Hash

T

able

+

Link

ed

List

Set

HashSet

T

reeSet

Link

edHashSet

List

Arra

yList

Link

edList

Deque

Arra

yDeque

Link

edList

Map

HashMap

T

reeMap

Link

edHashMap

7

List

y

List

y

[2℄:

-

klasa

A

rr

ayList<E>

extends

A

bstr

atList<E>

implements

List<E>,

R

andomA

ess,

Clone

able,

Seria-

lizable

eluj¡y

w

op

eraja

h

sw

ob

o

dnego

dostpu

do

elemen

w,

ale

w

olniejszy

przy

wsta

wianiu

i

usu

w

aniu

elemen

w

z

list

y:

publi

void

ensur

eCap

aity(int

minCap

aity),

pr

ote

te

d

void

r

emoveR

ange(int

fr

omIndex,

int

toIndex),

publi

void

trimT

oSize(),

p

ozostaªe

meto

dy

zadeklaro

w

ane

w

klasie

bazo

w

ej

i

implemen

to

w

an

y

h

in

terfejsa

h.

-

klasa

publi

lass

Linke

dList<E>

extends

A

bstr

atSe

quentialList<E>

implements

List<E>,

De-

que<E>,

Clone

able,

Serializable

opt

ymaln

y

dla

dostpu

sekw

enyjnego,

z

efekt

ywn

ymi

op

erajami

wsta

wiania

elemen

w

(i

i

h

usu

w

ania)

do

±ro

dk

a

list

y.

1

publi

lass

TestList

{

2

publi

stati

void

main (String [℄

args )

{

3

ArrayList

<Element

>

list1

=

new

ArrayList

<Element

>();

4

list1 .add (

new

Element

(

"0"

));

5

//

Exeption

:

java .lang .IndexOutOfBoundsExeption

:

Index :

10,

Size:

1

6

//

list1 .add (10,

new

Element (""

+

10) );

7

for

(

int

i

=

1;

i

<

10;

i ++)

8

list1 . add(

new

Element

(

""

+

i) );

9

System . out.println

(

"ArrayList

size

=

"

+

list1 .size () );

18

background image

10

System . out.println

(

"ArrayList

=

"

+

list1 );

11

list1 .add (5,

new

Element (

"NEW"

));

12

System . out.println

(

"ArrayList

=

"

+

list1 );

13

list1 .remove

(1);

14

System . out.println

(

"ArrayList

=

"

+

list1 );

15

list1 .remove

(

new

Element (

"NEW"

));

16

System . out.println

(

"ArrayList

=

"

+

list1 );

17

list1 .addAll

(Arrays .asList

(

new

Element (

"11"

) ,

new

Element (

"12"

)));

18

System . out.println

(

"ArrayList

=

"

+

list1 );

19

list1 .removeAll

( Arrays .asList (

new

Element

(

"4 "

),

new

Element

(

"5 "

)));

20

System . out.println

(

"ArrayList

=

"

+

list1 );

21

list1 .set (1,

new

Element (

"1"

)) ;

22

System . out.println

(

"ArrayList

=

"

+

list1 );

23

System . out.println

(

">>>

ontains

"

+

list1 .ontains

(

new

Element

(

"12 "

))) ;

24

System . out.println

(

">>>

indexOf

"

+

list1 .indexOf

(

new

Element (

"12"

) ));

25

System . out.println

(

">>>

get

"

+

list1 .get (8) );

26

System . out.println

(list1 . subList (2,

list1 .size ()

-

2) );

27

list1 .lear () ;

28

System . out.println

(

"ArrayList

=

"

+

list1 );

29

System . out.println

(

">>>

isEmpty

"

+

list1 .isEmpty

());

30

31

LinkedList

<Element

>

list2

=

new

LinkedList

<Element

>() ;

32

for

(

int

i

=

0;

i

<

10;

i ++)

33

swith

(i

%

2)

{

34

ase

0:

35

list2

.addFirst (

new

Element (

" "

+

i ));

36

break

;

37

ase

1:

38

list2

.addLast (

new

Element

(

""

+

i) );

39

break

;

40

}

41

System . out.println

(

"LinkedList

=

"

+

list2 );

42

System . out.println

(

">>>

getFirst

"

+

list2 .getFirst

() );

43

System . out.println

(

">>>

getLast

"

+

list2 .getLast

());

44

list2 .offer (

new

Element (

" *"

));

45

System . out.println

(

"LinkedList

=

"

+

list2 );

46

list2 .offerFirst

(

new

Element (

" -*-"

) );

47

System . out.println

(

"LinkedList

=

"

+

list2 );

48

list2 .offerLast

(

new

Element

(

"+*+ "

)) ;

49

System . out.println

(

"LinkedList

=

"

+

list2 );

50

System . out.println

(

">>>

peek

"

+

list2 . peek() );

51

System . out.println

(

">>>

peekFirst

"

+

list2 . peekFirst

());

52

System . out.println

(

">>>

peekLast

"

+

list2 .peekLast

() );

53

System . out.println

(

">>>

poll

"

+

list2 . poll() );

54

System . out.println

(

">>>

pollFirst

"

+

list2 . pollFirst

());

55

System . out.println

(

">>>

pollLast

"

+

list2 .pollLast

() );

56

list2 .push (

new

Element

(

"# "

));

57

System . out.println

(

"LinkedList

=

"

+

list2 );

58

System . out.println

(

">>>

pop

"

+

list2 .pop ()) ;

59

System . out.println

(

"LinkedList

=

"

+

list2 );

60

}

61

}

Przykªad

13:

sr/pl/kiele/tu/lab9/T

estList.ja

v

a

{link}

8

Zbiory

Zbiór

(ang.

set)

[2℄

z

deniji

nie

mo»e

za

wiera¢

wiej

ni»

jednego

egzemplarza

danej

w

arto±i,

pró-

ba

do

dania

k

olejn

y

h

egzemplarzy

iden

t

yzn

y

h

obiektó

w

zostanie

zignoro

w

ana,

o

zap

obiega

dublo

w

aniu

elemen

w

zbioru.:

19

background image

-

klasa

publi

lass

HashSet<E>

extends

A

bstr

atSet<E>

implements

Set<E>,

Clone

able,

Serializable,

-

Klasa

publi

lass

T

r

e

eSet<E>

extends

A

bstr

atSet<E>

implements

NavigableSet<E>,

Clone

able,

Se-

rializable.

Dla

k

olek

ji

wyk

orzystuj¡y

h

funk

j

miesza

j¡¡

nale»y

przesªoni¢

meto

dy

equals

()

i

hashCode

()

.

Dla

k

olek

ji

up

orz¡dk

o

w

an

y

h

nale»y

zaimplemen

to

w

in

terfejs

Comparable

lub

Comparator

.

1

publi

lass

TestSet

{

2

publi

stati

void

main (String [℄

args )

{

3

HashSet

<Integer >

set1

=

new

HashSet

<Integer >() ;

4

set1 .addAll ( Arrays .asList

(4,

3,

2,

1,

0,

0,

1,

2,

3,

4,

4,

3,

2,

1,

0)) ;

5

System . out.println

(set1 );

6

7

TreeSet

<Integer >

set2

=

new

TreeSet

<Integer >() ;

8

set2 .addAll ( Arrays .asList

(4,

3,

2,

1,

0,

0,

1,

2,

3,

4,

4,

3,

2,

1,

0)) ;

9

System . out.println

(set2 );

10

System . out.println

(

"first

"

+

set2. first ());

11

System . out.println

(

"last

"

+

set2 .last () );

12

System . out.println

(

"higher

"

+

set2 .higher (2) );

13

System . out.println

(

"lower

"

+

set2. lower (2)) ;

14

System . out.println

(

"floor

"

+

set2. floor (8)) ;

15

System . out.println

(

"eiling

"

+

set2 .eiling

(-8) );

16

System . out.println

(

"headSet

"

+

set2 .headSet

(2)) ;

17

System . out.println

(

"tailSet

"

+

set2 .tailSet

(2)) ;

18

System . out.println

(

"desendingSet

"

+

set2 .desendingSet

() );

19

}

20

}

Przykªad

14:

sr/pl/kiele/tu/lab9/T

estSet.ja

v

a

{link}

1

publi

lass

MyClass

implements

Comparable

<MyClass

>

{

2

private

int

i ;

3

4

publi

MyClass

(

int

i)

{

5

this

.i

=

i;

6

}

7

8

Override

publi

String

toString

()

{

9

return

"x"

+

i;

10

}

11

12

Override

publi

boolean

equals

(Objet

o )

{

13

if

(

this

.getClass

().isInstane

(o)

==

false

)

14

return

false

;

15

MyClass

tmp

=

(MyClass

)

o ;

16

System . out.println

(

this

+

".equals ( "

+

o

+

" )

=

"

+

(

this

. i

==

tmp. i));

17

return

this

. i

==

tmp. i;

18

}

19

20

Override

publi

int

hashCode

()

{

21

System . out.println

(

this

+

".hashCode

()

=

"

+

this

.i

%

4);

22

return

this

. i

%

4;

23

}

24

25

Override

publi

int

ompareTo

( MyClass

o )

{

26

System . out.println

(

this

+

".ompareTo

("

+

o

+

")

=

"

+

(

this

.i

-

o. i));

27

return

this

. i

-

o.i;

28

}

29

}

Przykªad

15:

sr/pl/kiele/tu/lab9/MyClass.ja

v

a

{link}

20

background image

1

publi

lass

TestSet2

{

2

publi

stati

void

main (String [℄

args )

{

3

HashSet

<MyClass >

set3

=

new

HashSet

<MyClass >() ;

4

System . out.println

(

"HashSet

addAll () "

);

5

set3 .addAll ( Arrays .asList

(

new

MyClass (4) ,

new

MyClass

(3),

6

new

MyClass

(2),

new

MyClass (1) ,

new

MyClass

(0)) );

7

System . out.println

(

"HashSet

toString

()"

);

8

System . out.println

(set3 );

9

System . out.println

(

"HashSet

add (new

MyClass (4) )"

);

10

set3 .add (

new

MyClass (4) );

11

System . out.println

(

"HashSet

toString

()"

);

12

System . out.println

(set3 );

13

System . out.println

(

"HashSet

ontains

(new

MyClass

(1))"

);

14

System . out.println

(set3 .ontains

(

new

MyClass

(1)) );

15

16

System . out.println

(

">-<>-<>-<

"

);

17

18

TreeSet

<MyClass >

set4

=

new

TreeSet

<MyClass >() ;

19

System . out.println

(

"TreeSet

addAll () "

);

20

set4 .addAll ( Arrays .asList

(

new

MyClass (4) ,

new

MyClass

(3),

21

new

MyClass

(2),

new

MyClass (1) ,

new

MyClass

(0)) );

22

System . out.println

(

"TreeSet

toString

()"

);

23

System . out.println

(set4 );

24

System . out.println

(

"TreeSet

add (new

MyClass (4) )"

);

25

set4 .add (

new

MyClass (4) );

26

System . out.println

(

"TreeSet

toString

()"

);

27

System . out.println

(set4 );

28

System . out.println

(

"TreeSet

ontains

(new

MyClass

(1))"

);

29

System . out.println

(set4 .ontains

(

new

MyClass

(1)) );

30

}

31

}

Przykªad

16:

sr/pl/kiele/tu/lab9/T

estSet2.ja

v

a

{link}

9

Map

y

Odwzoro

w

anie

Map

[2

℄:

grupa

para

obiektó

w

t

ypu

kluz

w

arto±¢,

p

ozw

ala

j¡a

na

wydob

yw

anie

w

arto±i

dla

znanego

kluza:

-

klasa

publi

lass

HashMap<K,V>

extends

A

bstr

atMap<K,V>

implements

Map<K,V>,

Clone

able,

Serializable,

-

Klasa

publi

lass

T

r

e

eMap<K,V>

extends

A

bstr

atMap<K,V>

implements

NavigableMap<K,V>,

Clo-

ne

able,

Serializable.

Dla

k

olek

ji

wyk

orzystuj¡y

h

funk

j

miesza

j¡¡

nale»y

przesªoni¢

meto

dy

equals

()

i

hashCode

()

.

Dla

k

olek

ji

up

orz¡dk

o

w

an

y

h

nale»y

zaimplemen

to

w

in

terfejs

Comparable

lub

Comparator

.

1

enum

Days {Monday ,

Tuesday ,

Wednesday

,

Thursday

,

Friday ,

Saturday

,

Sunday }

2

3

publi

lass

TestMap

{

4

publi

stati

void

main (String [℄

args )

{

5

HashMap

<Integer ,

String >

map1

=

new

HashMap < Integer ,

String >() ;

6

Days

days

[℄

=

Days .values

();

7

for

(

int

i

=

days .length

-

1;

i

>=

0

;

i --)

8

map1 .put (days [i ℄.ordinal () ,

days [i ℄.name ()) ;

9

System . out.println

(

"toString

()

:

"

+

map1 );

10

System . out.println

(

"entrySet

()

:

"

+

map1 .entrySet

()) ;

11

System . out.println

(

"keySet

()

:

"

+

map1 .keySet () );

12

System . out.println

(

"values

()

:

"

+

map1 .values () );

21

background image

13

14

TreeMap

<Integer ,

String >

map2

=

new

TreeMap < Integer ,

String >() ;

15

for

(

int

i

=

days .length

-

1;

i

>=

0

;

i --)

16

map2 .put (days [i ℄.ordinal () ,

days [i ℄.name ()) ;

17

System . out.println

(

"toString

()

:

"

+

map2 );

18

System . out.println

(

"entrySet

()

:

"

+

map2 .entrySet

()) ;

19

System . out.println

(

"keySet

()

:

"

+

map2 .keySet () );

20

System . out.println

(

"values

()

:

"

+

map2 .values () );

21

System . out.println

(

"firstEntry

()

:

"

+

map2. firstEntry

());

22

System . out.println

(

"lastEntry

()

:

"

+

map2 .lastEntry

() );

23

System . out.println

(

"firstKey

()

:

"

+

map2 .firstKey

()) ;

24

System . out.println

(

"lastKey

()

:

"

+

map2 .lastKey

());

25

System . out.println

(

"subMap

(2,

4)

:

"

+

map2. subMap (2,

4));

26

System . out.println

(

"headMap

(3)

:

"

+

map2 .headMap

(3)) ;

27

System . out.println

(

"tailMap

(3)

:

"

+

map2 .tailMap

(3)) ;

28

}

29

}

Przykªad

17:

sr/pl/kiele/tu/lab9/T

estMap.ja

v

a

{link}

1

publi

lass

TestMap2

{

2

publi

stati

void

main (String [℄

args )

{

3

HashMap

<MyClass ,

Integer >

map5

=

new

HashMap

<MyClass ,

Integer >() ;

4

for

(

int

i

=

0;

i

<

10

;

i ++){

5

System

.out. println (

" HashMap

put (new

MyClass

("

+

i

+

"))"

) ;

6

map5 .put (

new

MyClass

(i),

i);

7

}

8

System . out.println

(

"HashMap

toString

()"

);

9

System . out.println

(map5 );

10

System . out.println

(

"HashMap

put (new

MyClass (0) )"

);

11

map5 .put (

new

MyClass (0) ,

0);

12

System . out.println

(

"HashMap

toString

()"

);

13

System . out.println

(map5 );

14

System . out.println

(

"HashMap

get (new

MyClass (1) )"

);

15

map5 .get (

new

MyClass (1) );

16

System . out.println

(

">-<>-<>-<

"

);

17

TreeMap

<MyClass ,

Integer >

map6

=

new

TreeMap

<MyClass ,

Integer >() ;

18

for

(

int

i

=

0;

i

<

10

;

i ++){

19

System

.out. println (

" TreeMap

put (new

MyClass

("

+

i

+

"))"

) ;

20

map6 .put (

new

MyClass

(i),

i);

21

}

22

System . out.println

(

"TreeMap

toString

()"

);

23

System . out.println

(map6 );

24

System . out.println

(

"TreeMap

put (new

MyClass (0) )"

);

25

map6 .put (

new

MyClass (0) ,

0);

26

System . out.println

(

"TreeMap

toString

()"

);

27

System . out.println

(map6 );

28

System . out.println

(

"TreeMap

get (new

MyClass (1) )"

);

29

map6 .get (

new

MyClass (1) );

30

}

31

}

Przykªad

18:

sr/pl/kiele/tu/lab9/T

estMap2.ja

v

a

{link}

10

Iterator

Iterator

[2℄

to

obiekt,

którego

zadaniem

jest

przemieszzanie

si

p

o

sekw

enji

elemen

w

i

wybieranie

k

a»dego

z

nap

otk

an

y

h

elemen

w

b

ez

wiedzy

programist

y

u»ytk

o

wnik

a

lub

przejmo

w

ania

si

w

ewntrzn¡

struktur¡

takiej

sekw

enji.

22

background image

1

publi

lass

TestIterator

{

2

publi

stati

void

main (String [℄

args )

{

3

LinkedList

<Integer

>

list

=

new

LinkedList

<Integer

>();

4

list .addAll ( Arrays .asList

(0,

1,

2,

3,

4) );

5

System . out.println

(

"iterator

"

) ;

6

print (list .iterator

() );

7

System . out.println

(

"desending

iterator

"

);

8

print (list .desendingIterator

() );

9

System . out.println

(

"list

iterator "

) ;

10

print (list .listIterator

(2) );

11

12

System . out.println

(

"random

+

list

iterator

"

) ;

13

Random

r

=

new

Random

();

14

ListIterator

<Integer >

it

=

list .listIterator

();

15

for

(

int

i

=

0;

i

<

10;

i ++)

{

16

int

tmp

=

r .nextInt () ;

17

if

(tmp

>

0)

{

18

if

(it .hasNext () )

19

System .out .println

(

"next :

"

+

it .next ());

20

else

21

System .out .println

(

"Do

not

have

next"

);

22

}

else

{

23

if

(it .hasPrevious

() )

24

System .out .println

(

"previous

:"

+

it.previous

() );

25

else

26

System .out .println

(

"Do

not

have

previous "

);

27

}

28

}

29

}

30

31

stati

void

print

(Iterator

<Integer >

it)

{

32

System . out.print

(it.getClass

() .getSimpleName

()

+

"

"

) ;

33

while

( it.hasNext

())

34

System

.out. print (it. next()

+

"

"

);

35

System . out.println

();

36

}

37

}

Przykªad

19:

sr/pl/kiele/tu/lab9/T

estIterator.ja

v

a

{link}

11

Inne

k

olek

je

P

akiet

java.util

za

wiera

tak»e

nastpuj¡e

"starsze"

klasy:

ˆ

java.util.Ditionary,

ˆ

java.util.Hashtable,

ˆ

java.util.Pr

op

erties,

ˆ

java.util.Stak,

ˆ

java.util.V

e

tor,

oraz

jeden

"starszy"

in

terfejs:

ˆ

java.util.Enumer

ation,

który

za

wiera

dwie

meto

dy:

b

o

ole

an

hasMor

eElements(),

E

nextElement().

23

background image

12

Przykªado

w

a

tre±¢

lab

oratorium

Prosz

st

w

orzy¢

oraz

uru

homi¢

aplik

aj,

która

b

dzie

za

wiera¢

przykªady

wpro

w

adzania,

p

obierania

oraz

usu

w

ania

obiektó

w

klasy

np.

Samo

d

(Uw

aga:

tablie

tekstó

w,

t

yp

ó

w

prost

y

h,

t

yp

ó

w

opak

o

wuj¡y

h,

itp.

nie

b

o

eniane)

z:

-

Arra

yList,

-

HashSet,

-

T

reeMap.

Do

p

obierania

w

o

na

jmniej

w

jedn

ym

przypadku

p

o

winien

zosta¢

u»yt

y

iterator

zaimplemen

to

w

an

y

w

jednej

z

t

y

h

klas.

Prosz

zwró

szzególn¡

u

w

ag

na:

-

do

da

w

anie

duplik

ató

w

do

p

oszzególn

y

h

k

olek

ji,

-

spra

wdzanie

zy

obiekt

wn

y

(ró

wno

w

a»n

y)

zostaª

ju»

do

dan

y

.

Ustalanie

wno±i

(ró

wno

w

a»no±i)

obiektó

w,

p

oró

wn

yw

anie

obiektó

w

oraz

ustalanie

p

orz¡dku

p

o

winno

zosta¢

zrealizo

w

ane

w

opariu

o

n

umer

rejestrayjn

y

samo

ho

du

zapisan

y

w

p

ostai

tekstu,

dla

którego

wielk

o±¢

liter

p

o

winna

zosta¢

zignoro

w

ana.

Literatura

[1℄

S

hildt

Herb

ert,

Ja

v

a.

K

omp

endium

programist

y

.

W

ydanie

VI

I

I,

Helion,

2012

[2℄

E

k

el

Brue,

Thinking

in

Ja

v

a,

Edyja

p

olsk

a,

W

ydanie

IV,

Helion,

2006

[3℄

Horstmann

Ca

y

S.,

Cornell

Gary

,

Ja

v

a.

P

o

dsta

wy

,

W

ydanie

VI

I

I,

Helion,

2008

[4℄

Horstmann

Ca

y

S.,

Cornell

Gary

,

Ja

v

a.

T

e

hniki

zaa

w

anso

w

ane,

W

ydanie

VI

I

I,

Helion,

2009

[5℄

Blo

h

Josh

ua,

Ja

v

a.

Efekt

ywne

programo

w

anie.

W

ydanie

I

I,

Helion,

2009

[6℄

Bra

k

een

Da

vid,

Bark

er

Bret,

V

anhelsu

w

e

Laurene,

Ja

v

a.

T

w

orzenie

gier,

Helion,

2004

[7℄

Sªo

wnik

terminó

w

z

zakresu

obiekto

w

o±i.

Kazimierz

Subieta,

Ak

ademi

k

a

Oyna

W

yda

wniza

PLJ,

W

arsza

w

a

1999

[8℄

Sedgewi

k

Rob

ert,

W

a

yne

Kevin,

Algorytm

y

.

W

ydanie

IV,

Helion,

2012

[9℄

Krzysztof

Sa

ha,

In»ynieria

oprogramo

w

ania,

PWN,

2010

Materiaªy

do

przedmiotu

dostpne

na

strona

h:

h

ttp://a

hilles.tu.kiele.pl/

h

ttp://w

eaii-

mo

o

dle.tu.kiele.pl/

24


Document Outline


Wyszukiwarka

Podobne podstrony:
JAVA 09 klasy i obiekty(2)
notatki java 09
JAVA 09 Nieznany
JAVA 09 klasy i obiekty(2)
java 09
09 Obsługa baz danych w języku Java
Java praca domowa 09
09 Obsługa baz danych w języku Java
Java praca domowa 09
download Zarządzanie Produkcja Archiwum w 09 pomiar pracy [ www potrzebujegotowki pl ]
09 AIDSid 7746 ppt
09 Architektura systemow rozproszonychid 8084 ppt
TOiZ 09
Wyklad 2 TM 07 03 09
09 Podstawy chirurgii onkologicz

więcej podobnych podstron