JAVA 09 Nieznany

background image

Programo

w

anie

obiekto

w

e

(Ja

v

a)



9

1

T

yp

y

sparametryzo

w

ane

(ang.

generi s)

"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

y znie

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/kiel e/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»y ie

t

yp

ó

w

prost

y

h,

np.

int.

Problem

ten

mo»na

rozwi¡za¢

p

oprzez

u»y ie

klas

opak

o

wuj¡ y

h,

taki

h

jak

np.

Inte

ger.

U»y ie

Holder<E>

p

o

w

o

duje,

»e

nie

mo»em

y

uzysk

»adnej

do

datk

o

w

ej

informa ji

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

dziedzi z¡ e

(np.

A

tomi In

teger,

A

tomi Long,

BigDe imal,

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/kiel e/tu/lab9/HolderExtends.ja

v

a

{link}

T

yp

y

parametryzo

w

ane

[5

niezmienni ze.

W

p

oni»szym

przykªadzie

klasa

CCC

dziedzi zy

p

o

BBB,

która

z

k

olei

dziedzi zy

p

o

AAA.

Niezmienni zo±¢

t

yp

ó

w

parametryzo

w

an

y

h

ozna za,

»e

ta

hierar

hia

klas

nie

przenosi

si

na

Generi <AAA>,

Generi <BBB>

i

Generi <CCC> :

Generi <CCC>

nie

dziedzi zy

p

o

Generi <BBB>,

p

o

dobnie

Generi <BBB>

nie

dziedzi zy

p

o

Generi <AAA>.

1

publi

lass

TestGeneri s

{

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/kiel e/tu/lab9/T

estGeneri s.ja

v

a

{link}

2

Ograni zenia

Argumen

t

wielozna zn

y

[1℄



"T

aki

argumen

t

reprezen

tuje

nieznan

y

t

yp

i

ozna za

si

go

znakiem

zap

yta-

nia

(?

)."

"Ab

y

ustano

wi¢

górne

ograni zenie

wielozna zno± i

[1℄,

nale»y

za

wsze

k

orzysta¢

z

nastpuj¡ ej

ogólnej

p

osta i

argumen

tu

wielozna znego.

2

background image

<?

extends

klasa -bazowa

>

Elemen

t

klasa-bazo

w

a

to

nazw

a

klasy

,

stano

wi¡ ej

ograni zenie

górne.

P

amita

j,

p

o

dana

klasa

tak»e

za

wiera

si

w

ograni zeniu,

zyli

mo»e

zosta¢

u»yta

jak

o

argumen

t."

"Ab

y

ustano

wi¢

dolne

ograni zenie

wielozna zno± i

[1

℄,

u»yw

a

si

klauzuli

sup

er

w

deklara ji

wielozna z-

no± i.

Oto

górna

p

osta¢

takiego

rozwi¡zania.

<?

super

podklasa >

W

t

ym

przypadku

jak

o

argumen

t

dopusz zalne

t

ylk

o

te

klasy

,

które

zna

jduj¡

si

wy»ej

w

hierar

hii

dzie-

dzi zenia

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

opra o

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

Sta k<Numb

er>

numb

erSta k

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

ompila ji.

Zastoso

w

anie

pu-

shA

l

l(Col

le

tion<?

extends

E>

sr

)

w

klasie

Sta kSup

erExtends<E>

p

o

w

o

duje

usuni ie

tego

bªdu,

przy

jedno

zesn

ym

za

ho

w

aniu

k

on

troli

t

yp

ó

w.

Dla

Sta k<Numb

er>

numb

erSta k

meto

da

p

op()

umo»liwia

p

obieranie

obiektó

w

i

przypisanie

i

h

do

refe-

ren ji

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

ompila ji.

Zastoso

w

anie

p

o-

pA

l

l(Col

le

tion<?

sup

er

E>

dst)

w

klasie

Sta kSup

erExtends<E>

p

o

w

o

duje

usuni ie

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

du erextends,

onsumersup

er.

1

publi

lass

Sta k <E>

{

2

publi

Sta k ()

{

3

//

...

4

}

5

6

publi

void

push ( E

e)

{

7

//

...

8

}

9

10

publi

void

pushAll

(Colle tion

< 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

(Colle tion

<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

Sta k <Number

>

numberSta k

=

new

Sta k <Number

>();

34

numberSta k

. push (

new

Integer (1) );

35

Obje t

o

=

numberSta k

.pop ();

36

37

Colle tion

<Number

>

numberColle tion

=

new

HashSet

<Number >() ;

38

numberSta k

. pushAll (numberColle tion

);

39

numberSta k

. popAll (numberColle tion

);

40

41

Colle tion

<Integer

>

integerColle tion

=

new

HashSet <Integer

>() ;

42

//

a tual

argument

Colle tion

< Integer >

annot

be

onverted

to

Colle tion

<Number >

by

←֓

method

invo ation

onversion

43

//

numberSta k

.pushAll

(integerColle tion

);

44

45

Colle tion

<Obje t

>

obje tColle tion

=

new

HashSet

<Obje t >() ;

46

//

a tual

argument

Colle tion

< Obje t >

annot

be

onverted

to

Colle tion

<Number >

by

method

←֓

invo ation

onversion

47

//

numberSta k

.popAll

(obje tColle tion

) ;

48

}

49

}

Przykªad

4:

sr /pl/kiel e/tu/lab9/Sta

k.ja

v

a

{link}

1

publi

lass

Sta kSuperExtends

<E >

{

2

publi

Sta kSuperExtends

()

{

3

//

...

4

}

5

6

publi

void

push ( E

e)

{

7

//

...

8

}

9

10

publi

void

pushAll

(Colle tion

<?

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

(Colle tion

<?

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

Sta kSuperExtends

<Number >

numberSta k

=

new

Sta kSuperExtends

< Number >() ;

34

numberSta k

. push (

new

Integer (1) );

35

Obje t

o

=

numberSta k

.pop ();

36

37

Colle tion

<Number

>

numberColle tion

=

new

HashSet

<Number >() ;

4

background image

38

numberSta k

. pushAll (numberColle tion

);

39

numberSta k

. popAll (numberColle tion

);

40

41

Colle tion

<Integer

>

integerSta k

=

new

HashSet <Integer

>();

42

numberSta k

. pushAll (integerSta k

);

43

44

Colle tion

<Obje t

>

obje tSta k

=

new

HashSet

<Obje t >() ;

45

numberSta k

. popAll (obje tSta k

);

46

}

47

}

Przykªad

5:

sr /pl/kiel e/tu/lab9/Sta

kSup

erExtends.ja

v

a

{link}

3

Meto

dy

sparametryzo

w

ane

P

arametryza ja

mo»e

zosta¢

wyk

orzystana

w

stosunku

do

klas,

in

terfejsó

w,

meto

d,

a

na

w

et

k

onstruktoró

w.

1

publi

lass

Generi Methods

{

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/kiel e/tu/lab9/Generi Metho

ds.ja

v

a

{link}

4

K

olek

je

K

olek

ja

Colle tion

[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

dys yplin

y

k

olejki

(zwykle

p

ostuluje

ona

k

olejno±¢

iden

t

y zn¡

z

k

olejno± i¡

wsta

wiania

elemen

w).

5

background image



Odwzoro

w

anie

Map:

1

grupa

para

obiektó

w

t

ypu

klu z



w

arto±¢,

p

ozw

ala

j¡ a

na

wydob

yw

anie

w

arto± i

dla

znanego

klu za

.

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 .ClassCastEx eption

:

Cat

annot

be

ast

to

Dog

15

System

.out. println (d );

16

}

17

}

18

}

Przykªad

7:

sr /pl/kiel e/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

appli able

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/kiel e/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

uprosz zone

implemen

ta je

k

olek

ji

wyk

orzystuj¡ e

nastpuj¡ e

me

hanizm

y:

ˆ

tabli a



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

ta je

ma

t

ylk

o

harakter

p

ogl¡do

wy

i

niek

onie znie

zgo

dn

y

z

zastoso

w

an

ymi

w

bibliote e

standardo

w

ej

Ja

vy

.

1

publi

lass

MyArrayColle tion

<E >

{

6

background image

2

3

private

E[℄

obje ts

;

4

private

int

index

;

5

6

publi

MyArrayColle tion

(

int

initialCapa ity

)

{

7

obje ts

=

(E [℄)

new

Obje t

[initialCapa ity

℄;

8

}

9

10

publi

boolean

add (E

newObj

)

{

11

//

not

empty

spa e

12

if

(index

>=

obje ts . length )

13

return

false

;

14

15

obje ts

[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

(obje ts

[i℄. equals (obj ))

{

23

//

move

other

obje ts

24

System

.array opy

(obje ts

,

i

+

1,

obje ts ,

i,

index

-

i

-

1);

25

26

//

null

the

last

one

27

obje ts

[obje ts

.length

-

1℄

=

null

;

28

29

//

a tualize

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

+=

obje ts

[i℄;

43

if

(i

!=

index

-

1)

44

answer

+=

",

"

;

45

}

46

answer

+=

"℄ "

;

47

return

answer ;

48

}

49

}

Przykªad

9:

sr /pl/kiel e/tu/lab9/MyArra

yColle tio

n.ja

v

a

{link}

1

publi

lass

MyLinkedColle tion

< 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

//

he k

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

//

a tualize

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/kiel e/tu/lab9/MyLink

edColle tion.ja

v

a

{link}

1

publi

lass

MyHashColle tion

<E>

{

2

3

private

MyBu ket < E>[℄

bu kets ;

4

private

int

bu ketsQuantity

;

5

6

publi

MyHashColle tion

(

int

bu ketsQuantity

,

int

bu ketCapa ity

)

{

7

this

.bu ketsQuantity

=

bu ketsQuantity

;

8

this

.bu kets

=

( MyBu ket < E>[℄)

new

MyBu ket

[bu ketsQuantity

℄;

9

for

(

int

i

=

0;

i

<

bu ketsQuantity

;

i++)

10

this

.bu kets

[i℄

=

new

MyBu ket

<E>( bu ketCapa ity

);

11

}

12

13

/**

14

*

Adds

the

obje t

only

when

it

does

not

exists

in

the

olle tion

15

*

param

obj

the

obje t

whi h

should

be

added

16

*

return

true

if

the

obje t

was

added ,

and

false

otherwise

17

*/

18

publi

boolean

add (E

obj )

{

19

int

hashCode

=

obj .hashCode

();

20

int

bu ketNumber

=

hashCode

%

bu ketsQuantity

;

21

return

bu kets [bu ketNumber

℄.add (obj );

22

}

23

24

/**

25

*

Deletes

obje t

from

the

olle tion

26

*

param

obj

the

obje t

whi h

should

be

deleted

27

*

return

true

if

the

obje t

was

deleted

,

and

false

otherwise

28

*/

29

publi

boolean

delete ( E

obj )

{

30

int

hashCode

=

obj .hashCode

();

31

int

bu ketNumber

=

hashCode

%

bu ketsQuantity

;

32

return

bu kets [bu ketNumber

℄.delete

(obj );

33

}

34

35

Override

36

publi

String

toString

()

{

37

String

answer

=

"["

;

38

for

(

int

i

=

0;

i

<

bu kets

.length ;

i++)

{

39

answer

+=

bu kets

[i℄;

40

if

(i

!=

bu kets

.length

-

1)

41

answer

+=

",

"

;

42

}

43

answer

+=

"℄ "

;

44

return

answer ;

45

}

46

47

private

lass

MyBu ket

<F>

{

48

final

private

stati

int

NONE

=

-1;

49

private

F[℄

obje ts ;

50

51

publi

MyBu ket (

int

bu ketCapa ity

)

{

52

obje ts

=

( F[℄)

new

Obje t

[bu ketCapa ity

℄;

53

}

54

55

/**

56

*

Adds

the

obje t

only

when

it

does

not

exists

in

the

bu ket

57

*

param

obj

the

obje t

whi h

should

be

added

9

background image

58

*

return

true

if

the

obje t

was

added ,

and

false

otherwise

59

*/

60

publi

boolean

add (F

obj)

{

61

int

empty

=

NONE ;

62

63

for

(

int

i

=

0;

i

<

obje ts .length

;

i++)

{

64

//

he ks

whether

there

is

an

empty

spa e

65

if

(empty

==

NONE

&&

obje ts

[i℄

==

null

)

66

empty

=

i ;

67

68

//

he ks

whether

the

obje t

already

was

added

69

if

(obje ts

[i℄

!=

null

&&

obje ts

[i℄. equals (obj ))

70

return

false

;

71

}

72

//

not

empty

spa e

73

if

(empty

==

NONE )

74

return

false

;

75

76

//

adds

obje t

77

obje ts

[empty ℄

=

obj ;

78

return

true

;

79

}

80

81

/**

82

*

Deletes

obje t

from

the

bu ket

83

*

param

obj

the

obje t

whi h

should

be

deleted

84

*

return

true

if

the

obje t

was

deleted ,

and

false

otherwise

85

*/

86

publi

boolean

delete

(F

obj )

{

87

for

(

int

i

=

0;

i

<

obje ts .length

;

i++)

{

88

//

he ks

whether

the

obje t

was

added

89

if

(obje ts

[i℄

!=

null

&&

obje ts

[i℄. equals (obj ))

{

90

obje ts [i ℄

=

null

;

91

return

true

;

92

}

93

}

94

return

false

;

95

}

96

97

Override

98

publi

String

toString

()

{

Przykªad

11:

sr /pl/kiel e/tu/lab9/MyHashColle tion.ja

v

a

{link}

1

publi

lass

MyTreeColle tion

<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

tmpObje t

=

tmpNode

.obj ;

13

Comparable

<E >

tmpComparable

=

(Comparable

<E>) tmpObje t

;

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

tmpObje t

=

tmpNode

.obj ;

31

tmpComparable

=

(Comparable

<E>)

tmpObje t

;

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

tmpObje t

=

tmpNode

.obj ;

43

tmpComparable

=

(Comparable

<E>)

tmpObje t

;

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/kiel e/tu/lab9/MyT

reeColle tion.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.

on urr

ent.Blo

kingQueue,



java.util.

on urr

ent.T

r

ansferQueue,



java.util.De

que,



java.util.

on urr

ent.Blo

kingDe

que,

ˆ

java.util.Map,

który

rozszerza

in

terfejsy:



java.util.Sorte

dMap,



java.util.NavigableMap,



java.util.

on urr

ent.Con urr

entMap,



java.util.

on urr

ent.Con urr

entNavigableMap.

6.2

Colle tion<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.ora le. om/ja

v

ase/7/do

s/te

hnot es/gu ides/ olle t 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

in lusive),

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

omIn lusive,

E

toElement,

b

o

ole

an

toIn lusive),

ˆ

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

in lusive),

ˆ

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

era ja

si

nie

p

o

wiedzie

lub

zwra a

j¡ ym

sp

e jaln¡

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.ora le. 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

era ja

si

nie

p

o

wiedzie

lub

zwra a

j¡ ym

sp

e jaln¡

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

dziedzi zon

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.ora le. 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

in lusive),

ˆ

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

omIn lusive,

K

toKey,

b

o

ole

an

toIn lusive),

ˆ

NavigableMap<K,V>

tailMap(K

fr

omKey,

b

o

ole

an

in lusive),

ˆ

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

a t

lass

A

bstr

a tCol

le

tion<E>

extends

Obje

t

implements

Col

le

tion<E>,

ˆ

publi

abstr

a t

lass

A

bstr

a tSet<E>

extends

A

bstr

a tCol

le

tion<E>

implements

Set<E>,

ˆ

publi

abstr

a t

lass

A

bstr

a tList<E>

extends

A

bstr

a tCol

le

tion<E>

implements

List<E>,

ˆ

publi

abstr

a t

lass

A

bstr

a tSe

quentialList<E>

extends

A

bstr

a tList<E>,

ˆ

publi

abstr

a t

lass

A

bstr

a tMap<K,V>

extends

Obje

t

implements

Map<K,V>.

6.10

Klasy

k

onkretne

Implemen

ta je

k

olek

ji

1

:

In

terfa e

Hash

T

able

Resizable

Arra

y

Balan ed

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

a tList<E>

implements

List<E>,

R

andomA

ess,

Clone

able,

Seria-

lizable



 eluj¡ y

w

op

era ja

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

a ity(int

minCap

a ity),



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

a tSe

quentialList<E>

implements

List<E>,

De-

que<E>,

Clone

able,

Serializable



opt

ymaln

y

dla

dostpu

sekw

en yjnego,

z

efekt

ywn

ymi

op

era jami

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

//

Ex eption

:

java .lang .IndexOutOfBoundsEx eption

:

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

swit h

(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/kiel e/tu/lab9/T

estList.ja

v

a

{link}

8

Zbiory

Zbiór

(ang.

set)

[2℄

z

deni ji

nie

mo»e

za

wiera¢

wi ej

ni»

jednego

egzemplarza

danej

w

arto± i,

pró-

ba

do

dania

k

olejn

y

h

egzemplarzy

iden

t

y zn

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

a tSet<E>

implements

Set<E>,

Clone

able,

Serializable,

-

Klasa

publi

lass

T

r

e

eSet<E>

extends

A

bstr

a tSet<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

(

"des endingSet

"

+

set2 .des endingSet

() );

19

}

20

}

Przykªad

14:

sr /pl/kiel e/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

(Obje t

o )

{

13

if

(

this

.getClass

().isInstan e

(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/kiel e/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/kiel e/tu/lab9/T

estSet2.ja

v

a

{link}

9

Map

y



Odwzoro

w

anie

Map

[2

℄:

grupa

para

obiektó

w

t

ypu

klu z



w

arto±¢,

p

ozw

ala

j¡ a

na

wydob

yw

anie

w

arto± i

dla

znanego

klu za:

-

klasa

publi

lass

HashMap<K,V>

extends

A

bstr

a tMap<K,V>

implements

Map<K,V>,

Clone

able,

Serializable,

-

Klasa

publi

lass

T

r

e

eMap<K,V>

extends

A

bstr

a tMap<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/kiel e/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/kiel e/tu/lab9/T

estMap2.ja

v

a

{link}

10

Iterator

Iterator

[2℄



to

obiekt,

którego

zadaniem

jest

przemiesz zanie

si

p

o

sekw

en ji

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

en ji.

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

(

"des ending

iterator

"

);

8

print (list .des endingIterator

() );

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/kiel e/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.Di tionary,

ˆ

java.util.Hashtable,

ˆ

java.util.Pr

op

erties,

ˆ

java.util.Sta k,

ˆ

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

a j,

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:

tabli e

tekstó

w,

t

yp

ó

w

prost

y

h,

t

yp

ó

w

opak

o

wuj¡ y

h,

itp.

nie

b

d¡

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ó

sz zególn¡

u

w

ag

na:

-

do

da

w

anie

duplik

ató

w

do

p

osz zegó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

opar iu

o

n

umer

rejestra yjn

y

samo

ho

du

zapisan

y

w

p

osta i

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

Bru e,

Thinking

in

Ja

v

a,

Edy ja

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

Lauren e,

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

O yna

W

yda

wni za

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.kiel e.pl/

h

ttp://w

eaii-

mo

o

dle.tu.kiel e.pl/

24


Document Outline


Wyszukiwarka

Podobne podstrony:
JAVA 09 klasy i obiekty(2)
JAVA 06 Nieznany
ZJ 26 09 Nieznany
test notarialny 09 Nieznany
facade (fasada) [java wzorce p Nieznany
notatki java 09
JAVA 10 Nieznany
JAVA 08 Nieznany
plan opieki prenatalnej 2011 09 Nieznany
test?wokacko radcowski 09 Nieznany
podstawy programowania java id Nieznany
JAVA 09 klasy i obiekty(2)
java 09
JAVA 09
2015 04 09 08 25 05 01id 28644 Nieznany (2)

więcej podobnych podstron