0% found this document useful (0 votes)
41 views

Java 4 - Java's Type System and Collection Classes - Decrypted

This document is a chapter from a book about Java's type system and collection classes for software development. It discusses wrapper classes, strings, regular expressions, inner classes, iterators, enumerations, exception handling, generic types, lambda expressions, and the core collection classes in Java like ArrayList, LinkedList, HashSet, and HashMap. It includes examples, exercises, and problems for readers to practice and reinforce the concepts covered.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Java 4 - Java's Type System and Collection Classes - Decrypted

This document is a chapter from a book about Java's type system and collection classes for software development. It discusses wrapper classes, strings, regular expressions, inner classes, iterators, enumerations, exception handling, generic types, lambda expressions, and the core collection classes in Java like ArrayList, LinkedList, HashSet, and HashMap. It includes examples, exercises, and problems for readers to practice and reinforce the concepts covered.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 179

Java 4: Java’s type system and collection

classes
Software Development
Poul Klausen

Download free books at




POUL KLAUSEN

JAVA 4: JAVA’S
TYPE SYSTEM AND
COLLECTION CLASSES
SOFTWARE DEVELOPMENT

Download free eBooks at bookboon.com


2
Java 4: Java’s type system and collection classes: Software Development
1st edition
© 2017 Poul Klausen & bookboon.com
ISBN 978-87-403-1695-7
Peer review by Ove Thomsen, EA Dania

Download free eBooks at bookboon.com


3
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Contents

CONTENTS
Foreword 7

1 Introduction 9

2 Wrapper classes 11
Exercise 1 14

3 Strings 16
3.1 StringBuilder 18
3.2 StringTokenizer 19
Problem 1 20
3.3 Regular expressions 23
Exercise 2 36

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

Download free eBooks at bookboon.com


Click on the ad to read more
4
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Contents

4 Inner classes 38
4.1 Iterators 40
Exercise 3 47
Exercise 4 47
4.2 Example: ZipCodes 48

5 Enumerations 54
Exercise 5 58
Problem 2 59

6 Exception handling 70
6.1 Checked exceptions 74
6.2 Unchecked exceptions 81
Exercise 6 83

7 Generic types 85
Exercise 7 97
7.1 More on parameters 98
Exercise 8 99
7.2 Raw classes 100
7.3 Generic methods 101
Exercise 9 102
Problem 3 104
7.4 Bound parameter types 107
Exercise 10 110
7.5 Generic types and inheritance 111

8 Lambda expressions 115


8.1 Anonymous classes 115
8.2 Methods as parameters 119
8.3 Examples of lambda expressions 122
8.4 Java functional interfaces 129
8.5 Event handlers 129

Download free eBooks at bookboon.com


5
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Contents

9 Collection classes 131


9.1 Overview of the collection classes 131
9.2 ArrayList 134
9.3 LinkedList 138
Exercise 10 144
Problem 3 144
9.4 HashSet 145
9.5 TreeSet 149
Exercise 11 150
9.6 HashMap and TreeMap 153
9.7 PriorityQueue 155
Exercise 12 155
9.8 The algoritms 157
Exercise 12 161

10 Annotation 162

11 Packages 164

12 Final example 166


12.1 The task 166
12.2 Analysis 167
12.3 Design 170
12.4 Programming 174
12.5 Test 177
12.6 The last step 178

Download free eBooks at bookboon.com


6
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Foreword

FOREWORD
This book is the fourth in a series of books on software development. The programming
language is Java, and the language and its syntax and semantics fills obviously much, but
the books have also largely focus on the process and how to develop good and robust
applications. This book has, however, only to a lesser extent focus on the process, but more
on the language and numerous of details regarding Java as an object-oriented programming
language. The book is thus primarily for the programmer and presents techniques that can
help to ensure the development of robust and maintenance-friendly programs, but also
techniques needed to know in order to develop programs in a modern programming language.
You can also say that the current book deals with details on concepts, you have met in the
previous books, but only have been touched without going in depth. The book is a natural
continuation of the book Java 3 on object-oriented programming and thus assumes that
the reader has a knowledge corresponding to what is addressed in Java 3.

As the title says this series of books deals with software development, and the goal is to
teach the reader how to develop applications in Java. It can be learned by reading about
the subject and by studying complete sample programs, but most importantly by yourself
to do it and write your own programs from scratch. Therefore, an important part of the
books is exercises and problems, where the reader has to write programs that correspond to
the substance being treated in the books. All books in the series is built around the same
skeleton and will consist of text and examples and exercises and problems that are placed
in the text where they naturally belongs. The difference between exercises and problems is
that the exercises largely deals with repetitions of the substance that is presented in the text,
and furthermore it is relatively accurately described what to do. Problems are in turn more
loosely described, and are typically a little bigger and there is rarely any clear best solution.
These are books to be read from start to finish, but the many code examples, including
exercises and problems plays a central role, and it is important that the reader predict in
detail studying the code to the many examples and also solves the exercises and problems
or possibly just studying the recommended solutions.

All books ends with one or two larger sample programs, which focus primarily is on process
and an explanation of how the program is written. On the other hand appears the code only
to a limited extent – if at all – and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the development of programs
that are larger than the examples, which otherwise is presented, the aim of the concluding
examples also is to show program examples from varying fields of application.

Download free eBooks at bookboon.com


7
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Foreword

Most books also ends with an appendix dealing with a subject that would not be treated
in the books. It may be issues on the installation of software or other topics in computer
technology, which are not about software development, but where it is necessary to have
an introductory knowledge. If the reader already is familiar with the subject, the current
appendix can be skipped.

The programming language is, as mentioned Java, and besides the books use the following
products:

-- NetBeans as IDE for application development


-- MySQL to the extent there is a need for a database server (from the book Java 6
onwards)
-- GlassFish as a web server and application server (from the book Java 11 onwards)

It is products that are free of charge and free to install, and there is even talk about products,
where the installation is progressing all by itself and without major efforts and challenges.
In addition, there are on the web detailed installation instructions for all the three products.
The products are available on Windows and Linux, and it therefore plays no special role if
you use Linux or Windows.

All sample programs are developed and tested on machines running Linux. In fact, it plays
no major role, as both Java and other products work in exactly the same way whether the
platform is one or the other. Some places will be in the books where you could see that
the platform is Linux, and this applies primarily commands that concerning the file system.
Otherwise it has no meaning to the reader that the programs are developed on a Linux
machine, and they can immediately also run under Windows unless a program refers to
the file system where it may be necessary to change the name of a file.

Finally a little about what the books are not. It is not “how to write” or for that matter
reference manuals in Java, but it is as the title says books on software development. It is
my hope that the reader when reading the books and through the many examples can find
inspiration for how to write good programs, but also can be used as a source collection
with a number of examples of solutions to concrete everyday programming problems that
you regularly face as a software developer.

Download free eBooks at bookboon.com


8
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Introduction

1 INTRODUCTION
In Java 1 and Java 3, I have relatively detailed treated Java’s types, basically divided into
value types and reference types. For reasons of practical programming you can go on with
what has already been said about types, but Java defines a lot more, and it is the subject of
this book. It’s kind of concepts, which purpose are to develop programs of better quality,
and also to write programs with less code. Part of the following concepts I have already used
several times, so the book also serves as an explanation of the concepts that I previously
have used without exactly explaining what happens.

The main concepts are

-- Wrapper classes
-- Strings
-- Inner classes
-- Exception handling
-- Generic methods and classes
-- Lambda expressions
-- Collection klasser

Most of what follows is something that you can live without, but conversely something
that can make life easier as a programmer, but also kan help to increase the quality of the
programs developed.

The title of this series of books is software development, and the title suggests, I want to
focus on the development process and to a lesser extent the Java programming language.
This is not so in this book, as there is largely talk about details of the language itself, but
also concepts that are part of any modern programming language.

Download free eBooks at bookboon.com


9
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Introduction

Here it is worth thinking about that Java from the start was designed to should be an
object-oriented language that was simple and easy to learn. Java has been a success and
has over time progressed much as the language is in use in more and more areas from
both the development of complex computer applications over the web applications to the
development of apps for mobile phones. This of course has caused the development of a
number of new APIs, each of which aims to support the development of a specific category
of applications or support a particular technology. At the same time the basic concepts
of the language are developed, really as a natural evolution of what has happened with
other programming languages, and where there are more and more concepts added into
the language that is many of the concepts discussed in this book. In principle, it is fine
as it helps software developers, but conversely there is a price, namely that the language
becomes more complex and difficult to learn, and it is indeed a significant step away from
what was originally the idea of Java. It is worth thinking about, because in the worst case
it could mean that the language die because of its own success, and in fact there are several
precedents of programming languages that has had wide circulation, which has constantly
evolved to finally departing at death because they were too complex and hopeless to learn.
Everything in life is a balance.

Download free eBooks at bookboon.com


10
JAVA
JAVA
4: 4:
JAVA’S
JAVA’S
TYPE
TYPE
SYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTION CLASSES
CLASSES Wrapper
wrapperclasses
Classes

22 WRAPPER
WRAPPERCLASSES
CLASSES
Java’s
Java’stype
typesystem
systemconsists
consistsasasdiscussed
discussedininthe theprevious
previousbookbookofofa ahierarchy
hierarchyofofclasses
classeswith
with
the
theclass
classObject
Objectasasthe theroot.
root.Beside
Besidethere thereis isthe
thesimple
simpletypes
typesprimarily
primarilyforfornumbers
numbersand and
characters,
characters,andandininsomesomeplaces
placesit itis isa aproblem
problemthat thatthese
thesearearenot
notpart
partofofthe
theobject-oriented
object-oriented
class
classhierarchy.
hierarchy.ThereThereare,
are,therefore,
therefore,forforeach eachofofthe thesimple
simpletypes
typesdefined
defineda aclass
classthat
that
encapsulates
encapsulatesthe thesimple
simpletype.
type.For
Forexample
exampleis isthe theclass
classInteger
Integera aclass
classthat
thatencapsulates
encapsulatesananint.int.
These
Theseclasses
classesarearecalled
calledwrapper
wrapperclasses,
classes,andandbesides
besidestheytheyallow
allowthethevariables
variablesofofthethesimple
simple
types
typestotobebeused
usedininthe thesame
samewaywayasasother otherobjects,
objects,the thewrapper
wrapperclasses
classesdefines
definesa anumber
numberofof
useful
usefulmethods
methodsand andconstants
constantsforforthe thesimple
simpletypes.
types.

For
Forforforthe
thenumeric
numerictypes,
types,there
therearearefollowing
followingwrapper
wrapperclasses
classes

-- - Byte
Byte
-- - Short
Short
-- - Integer
Integer
-- - Long
Long
-- - Float
Float
-- - Double
Double

andandthethenames
namesshould
shouldtell
tellthe
theprimitive
primitivetype
typeasasthe
theclass
classencapsulates.
encapsulates.The
Thesixsixclasses
classesareare
allallderived
derivedfrom
fromthe
theclass
classNumber.
Number.

There
Therearearealso
alsowrapper
wrapperclasses
classestotochar
charandandboolean
booleanandandthey
theyarearecalled
calledrespectively
respectivelyCharacter
Character
and
andBoolean.
Boolean.Generally
Generallyarearethe
theuse
useofofthese
theseclasses
classeswithout
withoutmajor
majorchallenges,
challenges,but
butyou
youshould
should
study
studythem
themwell wellincluding
includingtotobebeaware
awareofofthe themethods
methodstheytheyoffer.
offer.AsAsananexample
exampleis isshown
shown
a amethod
methodwhich whichuses
usessome
someofofthethewrapper
wrapperclasses:
classes:

private static void test01()


{
Integer a = new Integer(23);
Integer b = 23;
print(a);
print(b);
Double x = 3.14;
print(x);
Character c = 'A';
print(c);
print(19);
}

Download free eBooks at bookboon.com


11 11
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
JAVA 4: JAVA’S CLASSES
JAVA’S TYPE
TYPE SYSTEM Wrapper classes
JAVA 4: SYSTEM
AND
AND COLLECTION CLASSES
COLLECTION CLASSES wrapper
wrapper Classes
Classes

private static void print(Object obj)


private static void print(Object obj)
{
{
System.out.println(obj.getClass().getName() + "
System.out.println(obj.getClass().getName() + " "
+ obj);
" + obj);
}
}

The
The method print() prints ananObject as the name ofofitsitsclass as well as itsitsvalue. The variable
The method
method print()
print() prints
prints an Object
Object asas the
the name
name of its class
class as
as well
well as
as its value.
value. The
The variable
variable
aaaisis an Integer object with the value 23, and you will notice that
is an Integer object with the value 23, and you will notice that it is created with new
an Integer object with the value 23, and you will notice thatititisiscreated
created with
with new
newasas
as
other
other objects. b is also an Integer object, but is assigned the int value 23 directly. Where it
other objects.
objects. bb is is also
also an
an Integer
Integer object,
object, butbut isis assigned
assigned the
the int
int value
value 23 23 directly.
directly. Where
Where it it
isislegal,
legal, ititisisbecause
because the
thecompiler
compiler uses
uses a aconcept
concept called
called auto
auto boxing.
boxing. This
This means
means that
thatwhen
when
is legal, it is because the compiler uses a concept called auto boxing. This means that when
the
the compiler sees that the variable bbisisofofthe type Integer, and you try totoassign a numerical
the compiler
compiler sees sees that
that the
the variable
variable b is of the the type
type Integer,
Integer, and
and you
you try
try to assign
assign aa numerical
numerical
value,
value, the compiler knows well that this value should be encapsulated in an Integerobject,
value, the
the compiler
compiler knows
knows well
wellthat
thatthis
this value
value should
should be
be encapsulated
encapsulated in
in an
an Integer
Integer object,
object,
and
and it will automatically execute b = new Integer( 23). The same applies for variables x and
and it it will
will automatically
automatically execute
execute bb == new
new Integer(
Integer( 23).
23). The
The same
same applies
applies forfor variables
variables xx and
and
c,c,using
using the
the auto
auto boxing
boxing totorespectively
respectively a aDouble
Double and
and a aCharacter.
Character.
c, using the auto boxing to respectively a Double and a Character.

Note
Noteespecially
Note especiallythe
especially thelast
the laststatement.
last statement.The
statement. Thecompiler
The compilerwill
compiler willlook
will lookfor
look fora aaprint()
for print()method
print() methodwith
method withanan
with an
int
intas a parameter. Such does not exist, but there is a print() method with an Object as
int as
as aa parameter.
parameter. Such
Such does
does not
not exist,
exist, but
but there
there is
is aa print()
print() method
method with with an
an Object
Object as as
parameter,
parameter, and
and the
thecompiler
compiler will
willautomatically
automatically boxes
boxes the
thevalue
value 19
19inin an
anInteger.
Integer.IsIsthe
the
parameter, and the compiler will automatically boxes the value 19 in an Integer. Is the
method
method performed, you get the result:
method performed,
performed, you
you get
get the
the result:
result:

java.lang.Integer 23
java.lang.Integer 23
java.lang.Integer
java.lang.Integer 23
23
java.lang.Double 3.14
java.lang.Double 3.14
java.lang.Character
java.lang.Character AA
java.lang.Integer 19
java.lang.Integer 19

The following
Thefollowing
The method
followingmethod creates
createsanan
methodcreates ArrayList
ArrayListofof
anArrayList objects
objectsofof
ofobjects the
ofthe type
thetype Number
typeNumber and
Numberand adds
andadds four
addsfour
four
items
itemstoto
items the
tothe list:
thelist:
list:

private
private static
static void
void test02()
test02()
{
{
ArrayList<Number>
ArrayList<Number> list
list =
= new
new ArrayList();
ArrayList();
list.add(2);
list.add(2);
list.add(3.14);
list.add(3.14);
list.add((short)5);
list.add((short)5);
list.add(7L);
list.add(7L);
for (Number t : list) print(t);
for (Number t : list) print(t);
}
}

Note
Note especially
Noteespecially that
especiallythat when
thatwhen the
whenthe list
listisis
thelist created,
created,itit
iscreated, itisis not
isnot necessary
notnecessary (but
necessary(but legally)
legally)toto
(butlegally) write:
towrite:
write:

ArrayList<Number> list =
ArrayList<Number> list = new
ArrayList<Number>();
new ArrayList<Number>();

Download free eBooks at bookboon.com


12

12
12
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Wrapper
wrapper classes
Classes

The
The compiler
compiler knows
knows that
that list
list should
should be
be used
used for
for objects
objects of
of the
the type
type Number.
Number. Also
Also note
note that
that
the
the four
four objects
objects that
that are
are added
added to to the
the list
list has
has aa different
different type.
type. IfIf the
the method
method isis executed
executed
isis the
the result:
result:

java.lang.Integer 2
java.lang.Double 3.14
java.lang.Short 5
java.lang.Long 7

Consider as the last example the following method


Consider as the last example the following method

private static void test03()


{
Integer[] arr = { 2, 3, 5, 7 };
int s = 0;

360°
for (Integer t : arr) s += t;
System.out.println(s);

.
}

thinking

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discoverfree
Download theeBooks
truth atatbookboon.com
www.deloitte.ca/careers
Click on the ad to read more
13
13
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA 4: JAVA’S TYPE
AND SYSTEM
AND COLLECTION
COLLECTION CLASSES
CLASSES Wrapper
wrapper classes
Classes
AND COLLECTION CLASSES wrapper Classes

Here
Here isis arr
arr an
an array
array of
of the
the type
type Integer,
Integer, which
which isis initialized
initialized with
with four
four objects.
objects. Note
Note that
that the
the
Here is arr an array of the type Integer, which is initialized with four objects. Note that the
compiler performes auto boxing. Next, a loop which determines the
compiler performes auto boxing. Next, a loop which determines the sum of the elements sum of the elements
compiler performes auto boxing. Next, a loop which determines the sum of the elements
of
of the
the array.
array. Here
Here isis ss an
an ordinary
ordinary intint variable,
variable, and
and you
you ought
ought really
really to
to write:
write:
of the array. Here is s an ordinary int variable, and you ought really to write:

s += t.intValue();
s += t.intValue();

but
but itit isis not
not necessary
necessary because
because thethe compiler
compiler use
use automatic
automatic unboxing.
unboxing. The
The compiler
compiler sees
sees that
that
but it is not necessary because the compiler use automatic unboxing. The compiler sees that
ss isis an
an int
int and
and know
know that
that itit must
must use
use the
the value
value of
of the
the Integer
Integer object
object t.t.
s is an int and know that it must use the value of the Integer object t.

EXERCISE
EXERCISE 1
EXERCISE 1
1
In
In this
this exercise
exercise you
you has
has to
to test
test the
the wrapper
wrapper classes
classes efficiency
efficiency compared
compared toto the
the primitive
primitive
In this exercise you has to test the wrapper classes efficiency compared to the primitive
types.
types. The representation of the primitive types as classes, other things being equal must
The representation of the primitive types as classes, other things being equal must
types. The representation of the primitive types as classes, other things being equal must
result in a performance loss.
result in a performance loss.
result in a performance loss.

Create
Create aa project
project that
that you
you can
can call
call Wrappers.
Wrappers. Add
Add the
the following
following method
method to
to the
the main
main class:
class:
Create a project that you can call Wrappers. Add the following method to the main class:

private static void test1()


private static void test1()
{
{
long t1 = System.nanoTime();
long t1 = System.nanoTime();
double sum = 0;
double sum = 0;
for (int i = 0; i < T; ++i) sum += Math.sqrt(i);
for (int i = 0; i < T; ++i) sum += Math.sqrt(i);
long t2 = System.nanoTime();
long t2 = System.nanoTime();
System.out.println(sum);
System.out.println(sum);
System.out.println(t2 – t1);
System.out.println(t2 – t1);
}
}

Here isis the


Here is the method
Here nanoTime() aa method
method that readsreads the hardware
hardware clock and
and returns the
the
the method
method nanoTime()
nanoTime() a method that that reads the
the hardware clock
clock and returns
returns the
time in
time in nano seconds.
seconds. T is a constant that that indicates thethe number of
of loop iterations
iterations to be
be
time in nano
nano seconds. TT isis aa constant
constant that indicates
indicates the number
number of loop
loop iterations to
to be
performed. Test
performed. Test the method
method by calling
calling it from main().
main(). The loop
loop must iterate
iterate many times
times
performed. Test the the method by by calling itit from
from main(). The
The loop must
must iterate many
many times
to get
to get a time that
that you can
can measure.
to get aa time
time that you
you can measure.
measure.

Then write
Then write aaa method
write method test2()
method test2()
Then that do exactly
exactly the same
same as test1()
test1() when the
the second and
and third
test2() that
that do
do exactly the
the same as
as test1() when
when the second
second and third
third
statement
statement should be replaced by:
statement should
should be
be replaced
replaced by:
by:

Double sum = 0D;


Double sum = 0D;
for (Integer i = 0; i < T; ++i) sum += new Double(Math.sqrt(i));
for (Integer i = 0; i < T; ++i) sum += new Double(Math.sqrt(i));

Compare the
Compare the two methods
methods and the
the time difference.
difference.
Compare the two
two methods and
and the time
time difference.

Download free eBooks at bookboon.com


14
14
14
JAVA
JAVA4:4:
JAVA JAVA’S
4:JAVA’S TYPE
JAVA’STYPE SYSTEM
TYPESYSTEM
SYSTEM
AND
AND COLLECTION
ANDCOLLECTION CLASSES
COLLECTIONCLASSES
CLASSES wrapper
Wrapper Classes
wrapperclasses
Classes

Thefollowing
The followingmethods
methodsdetermines
determinesthe
thefirst
firstprime
primenumber
numbergreater
greaterthan
thanororequal
equaltotoaaconstant
constantN:
N:

private
private static
static void
void test3()
test3()
{
{
long t1
long t1 = = System.nanoTime();
System.nanoTime();
long n =
long n = N; N;
while (!isPrime1(n))
while (!isPrime1(n)) ++n;
++n;
long t2 = System.nanoTime();
long t2 = System.nanoTime();
System.out.println(n);
System.out.println(n);
System.out.println(t2
System.out.println(t2 – – t1);
t1);
}
}

public
public static
static boolean
boolean isPrime1(long
isPrime1(long n)
n)
{
{
if
if (n
(n ==
== 22 ||
|| nn ==
== 33 ||
|| n
n ==
== 5
5 ||
|| nn ==
== 7)
7) return
return true;
true;
if (n
if (n <
< 11
11 ||
|| nn %
% 22 ==
== 0)
0) return
return false;
false;
for
for (long
(long t
t =
= 3,
3, m
m =
= (long)Math.sqrt(n)
(long)Math.sqrt(n) +
+ 1;
1; t
t <=
<= m;
m; t
t +=
+= 2)
2) if
if (n
(n %
% t
t ==
== 0)
0)
return false;
return false;
return
return true;
true;
}
}

The
Theidea
ideaisisthat
thatthe
themethod
methodtakestakesaalong
longtime,
time,ififNNisislarge.
large.Test
Testthe
themethod
methodfor forlarge
large
values
valuesofofN.
N.Finally,
Finally,write
writeaatest
testmethod
methodtest4(),
test4(),which
whichisissimilar
similartotothe
theabove,
above,but butuses
usesaa
prime
primemethod
methodisPrime2(Long
isPrime2(Longn), n),ieieaamethod
methodwherein
whereinthe
theparameter’s
parameter’stype
typeisisaawrapper
wrapperforfor
aalong. The loop for testing for prime numbers must also use variables of the
long. The loop for testing for prime numbers must also use variables of the type Long. type Long.
After
Afterwriting
writingthe
themethod,
method,compare
comparewith withtest3().
test3().

The
Theresult
resultshould
shouldbebethat
thatyou
youobserve
observethat
thatititcosts
costssomething
somethinginintimetimetotouse
usewrapper
wrapperobjects
objects
rather
ratherthan
thanprimitive
primitivevalues,
values,but
butactually
actuallysurprisingly
surprisinglylittle.
little.The
Thereason
reasonisisthat
thatthe
thecompiler
compiler
due
due to auto boxing knows the wrapper classes, and thus to a large extent can use themasas
to auto boxing knows the wrapper classes, and thus to a large extent can use them
ififititwere
wereprimitive
primitivetypes.
types.

Another
Anotherway
waytotomeasure
measurethe
thetime
timeisis

long
long t1
t1 =
= Calendar.getInstance().getTimeInMillis();
Calendar.getInstance().getTimeInMillis();

that
thatmeasure
measurethethetime
timeininmilliseconds.
milliseconds.Write
Writeaatest
testmethod
methodthat
thatcreates
createsan anArrayList<Integer>
ArrayList<Integer>
with
with aa million
million random
random integers.
integers. Test
Test how
how many
many milliseconds
milliseconds itit takes
takes toto sort
sort the
the list.
list.
Remember
Rememberthat thatyou
youcan
cansort
sortananArrayList
ArrayListasasfollows:
follows:

Collections.sort(list);
Collections.sort(list);

Note
Notethat
thatyou
youcan
cannot
notcreate
createananArrayList
ArrayListwith
withelements
elementsofofthe
thetype
typeint.
int.The
Thetype
typemust
mustbe
be
aaclass
classtype
typeasassuch
suchan
anInteger.
Integer.

Download free eBooks at bookboon.com


1515
15
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Strings
strIngs

3 STRINGS
The
The type
type String
String isis aa class,
class, although
although inin most
most cases
cases you
you uses
uses aa String
String as
as the
the other
other simple
simple data
data
types.
types. In
In most
most cases,
cases, thethe difference
difference isis not
not of
of great
great importance,
importance, butbut in
in some
some contexts
contexts itit isis
something
something youyou should
should be be aware
aware of.
of.

You
You should
should be be aware
aware that
that the
the class
class has
has aa number
number ofof methods
methods to to manipulate
manipulate strings,
strings, and
and
itit pays
pays toto investigate
investigate which
which methods
methods are are available.
available. Many
Many of of them
them II have
have used
used already
already and
and
more
more are are used
used inin the
the course
course ofof the
the books.
books. The
The class
class also
also have
have useful
useful static
static methods.
methods. II will
will
not
not discuss
discuss these
these methods
methods here,
here, but
but the
the application
application will
will appear
appear inin the
the books
books examples,
examples, and
and
I’ve already used many of these
I’ve already used many of these methods. methods.

IfIf you
you examine
examine the
the documentation
documentation for
for the
the String
String class,
class, you
you will
will see
see the
the definition
definition

public final class String


extends Object implements Serializable, Comparable<String>, CharSequence

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

Download free eBooks at bookboon.com


Click on the ad to read more
16
16
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
JAVA 4:
JAVA 4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Strings
strIngs
AND COLLECTION
AND COLLECTION CLASSES
CLASSES strIngs
strIngs

This
Thismeans
This meansthat
means thatthe
that theclass
the classisis
class isdefined
definedfinal
defined finaland
final andthus
and thuscan
thus cannot
can notbe
not beinherited.
be inherited.Moreover,
inherited. Moreover,you
Moreover, youcan
you can
can
see
seethat
thatthe
the class
classimplements
implements three
three interfaces.
interfaces.The
The second
secondsays
says that
thatstrings
stringscan
can
see that the class implements three interfaces. The second says that strings can be orderedbe
beordered
ordered
and
andexactly
exactlytells
tellsthe
theinterface,
interface,that
thatthe
theclass
classimplements
implementsaamethod
method
and exactly tells the interface, that the class implements a method

compareTo(String
compareTo(String str)
compareTo(String str)
str)

which
whichisisthe thecomparison
comparisonmethodmethodfor forstrings
stringsthatthatcompares
comparesstrings
stringsininalphabetical
alphabeticalorder. order.
which is the comparison method for strings that compares strings in alphabetical order.
When
Whenthe
When theclass
the classString
class Stringimplements
String implementsthis
implements thisinterface,
this interface,itit
interface, itmeans
meansamong
means amongother
among otherthings
other thingsthat
things thatstrings
that strings
strings
can
can be sorted with Java’s sorting methods. The last interface tells something about whataaa
can bebesorted
sorted with
with Java’s
Java’s sorting
sorting methods.
methods. The
The last
lastinterface
interface tells
tellssomething
something about
about what
what
string
stringis.is.Internally
InternallyisisaaString
Stringisisan
anarray
arrayofofcharacters,
characters,and andyouyoucancanrefer
refertotothe
theindividual
individual
string is. Internally is a String is an array of characters, and you can refer to the individual
characters
characterswith withthe
themethod
methodcharAt().
charAt().AnAnimportant
importantcharacteristic
characteristicofofthetheclass
classString
Stringisisthat
that
characters with the method charAt(). An important characteristic of the class String is that
itit
itisis
isimmutable,
immutable,and
immutable, andthat
and thatmeans
that meansthat
means thathave
that haveyou
have youcreated
you createdaaaString,
created String,itit
String, itcan
cannot
can notbe
not bechanged.
be changed.For
changed. For
For
instance
instance you
you can
can not
not change
change a acharacter
character in
in a astring.
string. If
Ifyou,
you, for
forexample
example
instance you can not change a character in a string. If you, for example has the string has
has the
the string
string

String
String s = "abcdefg";
String s
s =
= "abcdefg";
"abcdefg";

and
andyou
youwant
wanttotochange
changethe
thecharacter
characterddtotoaabig
bigD,
D,you
youmust
mustwrite
writesomething
somethinglike
likethe
the
and you want to change the character d to a big D, you must write something like the
following:
following:
following:

s
s =
= s.substring(0,
s.substring(0, 3)
3) +
+ "D"
"D" +
+ s.substring((4));
s.substring((4));
s = s.substring(0, 3) + "D" + s.substring((4));

Here,
Here,you you
youtaketake
takeaaasubstring
substring consisting
consistingofof
substringconsisting the
ofthe first
thefirst three
firstthree characters
threecharacters
charactersandand concatenates
concatenatesitit
andconcatenates with
itwith
with
Here,
string consisting
stringconsisting of
consistingofofthe the character
thecharacter
characterD. D. This
D.This result
Thisresult is
resultisisthen then concatenated
thenconcatenated
concatenatedwith with
withthethe substring
thesubstring
substring
string
consisting of all characters from index 4 to the end of the string. Concatenation of two
consistingofofall
consisting allcharacters
charactersfrom fromindex
index44totothe theend endofofthe thestring.
string.Concatenation
Concatenationofoftwo two
strings create a new String object, and the above statement will create two objects, and the
stringscreate
strings createaanewnewString
Stringobject,
object,and
andthe
theabove
abovestatement
statementwill willcreate
createtwo
twoobjects,
objects,and andthethe
variable s is set
variables sisisset to refer
settotorefer to the
refertotothe result
theresult object
resultobject instead
objectinstead of
insteadofofthe the original
theoriginal string.
originalstring. At
string.At the
Atthe class
theclass in this
classininthis
this
variable
way is immutable
wayisisimmutable
immutablesoundssounds complicated,
soundscomplicated,
complicated,and and it is at times
andititisisatattimes
timestoo,too, but
too,but the
butthe reason
thereason is performance,
reasonisisperformance,
performance,
way
where it is important that the creation of string is effective and a string not fills more than
whereititisisimportant
where importantthat thatthe
thecreation
creationofofstring
stringisiseffective
effectiveandandaastring
stringnot
notfills
fillsmore
morethanthan
necessary. In practice it is not something you think much about when the compiler largely
necessary.InInpractice
necessary. practiceititisisnotnotsomething
somethingyou youthink
thinkmuchmuchaboutaboutwhen
whenthe thecompiler
compilerlargely
largely
treats strings
treatsstrings as other
stringsasasother simple
othersimple types,
simpletypes, and
types,and as the
andasasthe String
theString class
Stringclass has
classhas many
hasmany methods.
manymethods.
methods.
treats

However, in special cases, it is important that you are aware that manipulation of strings
However,ininspecial
However, specialcases,
cases,ititisisimportant
importantthat
thatyou
youare
areaware
awarethat
thatmanipulation
manipulationofofstrings
strings
constantly creates new objects. If you considers the following method (a method in the
constantlycreates
constantly createsnew
newobjects.
objects.IfIfyouyouconsiders
considersthe
thefollowing
followingmethod
method(a(amethod
methodininthethe
project Strings):
projectStrings):
Strings):
project
private
private static
static void
void test01()
test01()
private static void test01()
{
{
{
String
String s
s == "";
"";
String s = "";
long
long t1
t1 =
= getTime();
getTime();
long t1 = getTime();
for
for (int
for (int i
(int i =
i = 0;
= 0; i
0; i <
i < 100000; ++i)
< 100000;
100000; ++i) s
++i) s +=
+= "A";
s += "A";
"A";

Download free eBooks at bookboon.com


1717
17
17
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
JAVA CLASSES
4: JAVA’S TYPE SYSTEM Strings
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES strIngs
AND COLLECTION CLASSES strIngs

long
long t2
t2 =
= getTime();
getTime();
System.out.println(t2
System.out.println(t2 –
– t1);
t1);
}
}

public
public static
static long
long getTime()
getTime()
{
{
return
return new
new GregorianCalendar().getTimeInMillis();
GregorianCalendar().getTimeInMillis();
}
}

itit creates
createsa aastring
itcreates string consisting
stringconsisting 100,000
consisting100,000 occurrences
occurrencesofof
100,000occurrences the
ofthe character
characterA,A,
thecharacter A,butbut the
butthe string
stringisis
thestring built
isbuilt
built
byby adding
byadding
addingone one character
onecharacter a
charactera atime. time. The
time.The original
Theoriginal string
originalstring s is extended
strings sisisextended
extendedby by concatenation
byconcatenation
concatenation(the (the
(the
operator
operator+=).
operator +=). This
+=).This means
Thismeans
meansthatthat the
thatthe method
themethod creates
methodcreates 100,000
creates100,000
100,000new new objects,
newobjects, and
objects,and each
andeach time
eachtime must
timemust
must
create
createa aanew
create new object
newobject
objecton on
onthethe heap,
theheap, and
heap,and
andthethe contents
contentsofof
thecontents ofthethe old
theold object
oldobject
objectmustmust
mustbebe copied
copiedtoto
becopied to
the new
thenew
the object.
newobject.
object.On On
Onboth both sides
bothsides of the
sidesofofthe loop,
theloop, I have
loop,I Ihave read
haveread
readthethe hardware
thehardware clock
hardwareclock and
clockand finally
andfinally the
finallythe
the
method prints
methodprints
method how
printshow
howlong long it took
longitittook to execute
tooktotoexecute
executethethe loop.
theloop. It depends
loop.ItItdepends of course
dependsofofcourse of the
courseofofthe machine,
themachine,
machine,
but
buton
but on a (not
ona a(not very
(notvery
veryfast)fast) machine,
fast)machine, it
machine,itithas has taken
hastaken 6554
taken6554 milliseconds
6554milliseconds
millisecondsand and therefore
andtherefore about
thereforeabout
about6½ 6½

seconds, which
whichisis
seconds,which
seconds, isa aalong
long time.
longtime.
time.

3.1 STRINGBUILDER
3.1 STRINGBUILDER
3.1 STRINGBUILDER
Now,
Now,itit
Now, itisis
isofof course
coursea aabit
ofcourse bit extremely
extremelytoto
bitextremely build
builda aastring
tobuild string
stringonon this
onthis way,
thisway, but
way,but there
butthere are
thereare applications
areapplications
applications
where there
wherethere
where is a
thereisisa aneedneed to perform
needtotoperform
performmanymany operations
manyoperations
operationson on strings.
onstrings. To
strings.To this
Tothis end,
thisend, there
thereisis
end,there isa aaclass
class
class
StringBuilder,
StringBuilder,which
StringBuilder, which is a class
whichisisa aclass where
classwhere
whereyouyou
youcancan manipulate
canmanipulate
manipulatethe the individual
theindividual characters
individualcharacters in a string,
charactersinina astring,
string,
and represents
representsa aastring
andrepresents
and string that
stringthat can
canbebe
thatcan expanded
beexpanded without
expandedwithout
withoutthethe need
needtoto
theneed create
createa aanew
tocreate new object.
object.InIn
newobject. In
principle, a StringBuilder
principle,a aStringBuilder
principle, is
StringBuilderisisthe the same
thesame as an ArrayList,
sameasasananArrayList,
ArrayList,butbut simply
butsimply a list
simplya alist where
listwhere
wherethethe elements
theelements
elements
are of the
areofofthe
are thetypetype char.
typechar. If the
char.IfIfthe task
thetask was
taskwas to build
wastotobuild a string
builda astring as above,
stringasasabove, you
above,you could
youcould
coulddo do it with
doititwith
withthe the
the
following method,
followingmethod,
following method,which which
whichusesuses a StringBuilder:
usesa aStringBuilder:
StringBuilder:

private
private static
static void
void test02()
test02()
{
{
StringBuilder
StringBuilder b b =
= new
new StringBuilder();
StringBuilder();
long t1 = getTime();
long t1 = getTime();
for
for (int
(int i i == 0;
0; i
i <
< 100000;
100000; ++i)
++i) b.append("A");
b.append("A");
String s = b.toString();
String s = b.toString();
long
long t2
t2 = = getTime();
getTime();
System.out.println(t2
System.out.println(t2 – – t1);
t1);
}
}

Download free eBooks at bookboon.com


18

18
18
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Strings

If you execute the method on the same machine, it takes 9 milliseconds, and thus there is
a very big difference in performance. You should note that the algorithm (method) is the
same, and that the improvement therefore solely due to the class StringBuilder, and that it
is no longer necessary to create and copy the 100000 objects.

In the two methods I have read the hardware clock using the method getTime(), which returns
the number of milliseconds after 00:00:00:000. The method creates a GregorianCalendar
object that is defined by the interface Calendar. The constructor of the class GregorianCalendar
initializes the object by reading the hardware clock. The type defines and represents a date
and time for a particular day. A Calendar has many methods, and here among other things
a method get() which returns a specific value for a time where a constant indicates the value
you want to get. The class GregorianCalendar is the standard class in Java for dates and times.

3.2 STRINGTOKENIZER
Java has a class for treatment of strings called StringTokenizer. I have used the class previously
in the last example in the book Java 3 to split a string into tokens, but it is generally used
to split a string in substrings, which are separated by one or more separation characters.
As an example, the following method defines a string that consists of integers separated by
either a comma or semicolon:

AXA Global
Graduate Program
Find out more and apply

Download free eBooks at bookboon.com


Click on the ad to read more
19
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA
AND 4:
4: JAVA’S
JAVA’S TYPE
COLLECTION TYPE SYSTEM
SYSTEM
CLASSES Strings
AND COLLECTION CLASSES
AND COLLECTION CLASSES strIngs
strIngs

private
private static
static void
void test03()
test03()
{
{
StringTokenizer
StringTokenizer tk
tk =
= new
new StringTokenizer("2;3,5;7,11;13,17;19",
StringTokenizer("2;3,5;7,11;13,17;19", ",;");
",;");
int sum = 0;
int sum = 0;
while
while (tk.hasMoreTokens())
(tk.hasMoreTokens()) sum
sum +=
+= Integer.parseInt(tk.nextToken());
Integer.parseInt(tk.nextToken());
System.out.println(sum);
System.out.println(sum);
}
}

The
Themethod
The methoduses
method usesa aaStringTokenizer
uses StringTokenizertoto
StringTokenizer tosplit
splitthe
split thestring
the stringinin
string innumbers
numbersand
numbers anddetermine
and determinetheir
determine theirsum.
their sum.
sum.

PROBLEM
PROBLEM11
PROBLEM 1
InIn
InJava
Java2,2,
Java 2,I IIhave
havecreated
have createda aaclass
created classlibrary
class librarynamed
library namedPaLib.
named PaLib.InIn
PaLib. Inthis
thisproblem,
this problem,you
problem, youmust
you mustexpand
must expand
expand
this
thislibrary
this librarywith
library witha aanew
with newclass.
new class.
class.

Start
Startwith
Start withanan
with ancopy
copyofof
copy ofthe
thelibrary
the libraryand
library andopen
and openthe
open thecopy
the copyinin
copy inNetBeans.
NetBeans.To
NetBeans. Tothe
To thepackage
the packagepalib.
package palib.
palib.
util
utilyou
util youmust
you must add
must add the
add the following
the following class,
following class, which
class, whichdefines
which definessome
defines some methods
some methods that
methods that may
that maybe
may beuseful
usefulfor
be useful for
for
manipulating
manipulatingstrings:
manipulating strings:
strings:

package
package palib.util;
palib.util;

import
import java.util.*;
java.util.*;
/**
/**
*
* Class
Class defining
defining methods
methods of
of operations
operations on on strings.
strings.
*/
*/
public
public abstract
abstract class
class Str
Str
{
{
/**
/**
*
* Method
Method which
which cuts
cuts off
off a a string
string of
of specific
specific length
length n.
n.
*
* If the string length is greater than n, the operation
If the string length is greater than n, the operation is
is ignored
ignored and
and the
the
* string is returned unchanged.
* string is returned unchanged.
*
* @param
@param ss The
The string
string that
that must
must be
be cut
cut off
off
* @param n The length of the resulting
* @param n The length of the resulting string string
*
* @return
@return The
The string
string cut
cut to
to length
length nn
*/
*/
public
public static
static String
String cut(String
cut(String s, s, int
int n)n)
{
{


}
}

/**
/**
*
* Method
Method as
as left
left adjusts
adjusts a a string
string inin a
a field
field of
of width
width n.
n.
* If
* If the
the string length
string length is
is greater
greater than
than n,
n, the
the operation
operation isis ignored
ignored and
and the
the
* string
* string is returned unchanged.
is returned unchanged.
* @param
* @param s The
s The string
string needs
needs that
that has
has to
to bebe adjusted
adjusted
*
* @param
@param n The width of the field
n The width of the field
* @param
* @param c The
c The padding
padding char
char that
that field
field has
has to
to be
be filled
filled with.
with.

Download free eBooks at bookboon.com


20
20
20
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Strings
AND COLLECTION CLASSES strIngs

* @return The string left adjusted in a field of width n.


*/
public static String left(String s, int n, char c)
{

}

/**
* Method as right adjusts a string in a field of width n.
* If the string length is greater than n, the operation is ignored and the
* string is returned unchanged.
* @param s The string needs that has to be adjusted
* @param n The width of the field
* @param c The padding char that field has to be filled with.
* @return The string right adjusted in a field of width n.
*/
public static String right(String s, int n, char c)
{

}

/**
* Method which centers a string in a field of width n.
* If the string length is greater than n, the operation is ignored and the
* string is returned unchanged.
* @param s The string needs that has to be adjusted
* @param n The width of the field
* @param c The padding char that field has to be filled with.
* @return The string adjusted center in a field of width n.
*/
public static String center(String s, int n, char c)
{

}

/**
* Returns the sum of a number of decimal numbers delimited by the character c.
* If an item (number) can not be parsed into a double, it should just be
* igonered.
* @param s String representing a number of numbers separated by the character c
* @param c The character that separates the numbers
* @return The sum of the numbers
*/
public static double sum(String s, char c)
{

}
}

Download free eBooks at bookboon.com


21
21
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Strings
strIngs

You
Youshould
shouldnote
notethat
thatthe
theclass
classisisdefined
definedabstract.
abstract.This
Thismeans
meansthat
thatthe
theclass
classcan
cannot
notbebe
instantiated,
instantiated,and
andsince
sinceitithas
hasonly
onlystatic
staticmethods,
methods,ititmakes
makesnor
norno
nosense.
sense.

Once
Onceyou
youhave
havewritten
writtenthe
theclass,
class,you
youshould
shouldtest
testyour
yourclass
classlibrary
librarywith
withthe
thefollowing
followingtest
test
program:
program:

package strprogram;

import palib.util.*;

public class StrProgram


{
public static void main(String[] args)
{
String s = "1234567890";
System.out.println(Str.cut(s, 8));
System.out.println(Str.left(s, 15, '#'));
System.out.println(Str.right(s, 15, '#'));
System.out.println(Str.center(s, 15, '#'));
System.out.println(Str.sum("2 + 3 + 5.25 + 7.75", '+'));
}
}

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

Download free eBooks at bookboon.com


Click on the ad to read more
2222
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
JAVA
AND 4: JAVA’S TYPE
ANDCOLLECTION
COLLECTION SYSTEM
CLASSES
CLASSES Strings
strIngs
AND COLLECTION CLASSES strIngs

12345678
12345678
1234567890#####
1234567890#####
#####1234567890
#####1234567890
###1234567890##
###1234567890##
18.0
18.0

I Ihave
havecalled
calledthe
thetest
testproject
projectStrProgram.
StrProgram.
I have called the test project StrProgram.
3.3
3.3 REGULAR
REGULAREXPRESSIONS
EXPRESSIONS
3.3 REGULAR EXPRESSIONS
AAregular
regularexpression
expressionisisa aconcept
conceptthatthatisisclosely
closelyrelated
relatedtotostrings,
strings,and
andyou youcan
canuse
useregular
regular
A regular expression is a concept that is closely related to strings, and you can use regular
expressions
expressionstotodefine
definepatterns
patternsforforstrings,
strings,andandthen
thenyouyoucancanask
askififanother
anotherstring
stringhas
hasone
oneoror
expressions to define patterns for strings, and then you can ask if another string has one or
more
moresubstrings
substringsthat
thatmatch
matchthisthispattern.
pattern.InInJava,
Java,regular
regularexpressions
expressionsare areimplemented
implementedby bytwo
two
more substrings that match this pattern. In Java, regular expressions are implemented by two
classes,
classes,which
whichare
arecalled
calledPattern
Patternand
andMatcher.
Matcher.The Theclasses
classesare
aredefined
definedininthethepackage
packagejava.util.
java.util.
classes, which are called Pattern and Matcher. The classes are defined in the package java.util.
regex.
regex.The
Thesyntax
syntaxfor
forregular
regularexpressions
expressionsisisrelatively
relativelycomplex
complexand andthetheconcept
conceptisisintroduced
introduced
regex. The syntax for regular expressions is relatively complex and the concept is introduced
most
mosteasily
easilyby
bymeans
meansofofexamples.
examples.I Iwill
willtherefore
thereforestart
startwith
withthethefollowing
followingmethod:
method:
most easily by means of examples. I will therefore start with the following method:
private static void test04()
private static void test04()
{
{
while (true)
while (true)
{
{
String udt = enter("Regular expression: ");
String udt = enter("Regular expression: ");
if (udt.length() == 0) break;
if (udt.length() == 0) break;
Pattern pattern = Pattern.compile(udt);
Pattern pattern = Pattern.compile(udt);
while (true)
while (true)
{
{
String str = enter("Search string: ");
String str = enter("Search string: ");
if (str.length() == 0) break;
if (str.length() == 0) break;
Matcher matcher = pattern.matcher(str);
Matcher matcher = pattern.matcher(str);
boolean found = false;
boolean found = false;
while (matcher.find())
while (matcher.find())
{
{
System.out.printf(
System.out.printf(
"The text \"%s\" found with start index %d and end index %d\n",
"The text \"%s\" found with start index %d and end index %d\n",
matcher.group(), matcher.start(), matcher.end());
matcher.group(), matcher.start(), matcher.end());
found = true;
found = true;
}
}
if(!found) System.out.println("No match found");
if(!found) System.out.println("No match found");
}
}
}
}
}
}

Download free eBooks at bookboon.com


2323
23
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND COLLECTION CLASSES Strings
AND COLLECTION
AND COLLECTION CLASSES
CLASSES strIngs
strIngs

The
The method isisaasimple console application that runs in aadialog with the user. ItItuses the
The method
method is a simple
simple console
console application
application thatthat runs
runs in
in a dialog
dialog with with the
the user.
user. It uses
uses the
the
method
method enter(), which isisaasimple input method for entering aastring. The program runs in
method enter(), which is a simple input method for entering a string. The program runs in
enter(), which simple input method for entering string. The program runs in
an infinite
an infinite loop.
infinite loop. For
loop. For each
For each repetition,
each repetition, the
repetition, the user
the user must
user must enter
must enter a string
enter aa string for
string for a regular
for aa regular expression,
regular expression,
expression,
an
and if it is not the empty string the program creates a Pattern object that represents the
and if it is not the empty string the program creates creates aa Pattern
Pattern object
object that
that represents
represents thethe
regular expression. This is done by using a static method compile() in the class Pattern.
regular expression. This is done by using a static method compile() in the class Pattern.
the class Pattern.
Next,
Next, the program starts an inner loop, which isisalso an infinite loop. Here the user must
Next, the program starts an inner loop, which is also an infinite loop. Here the
the program starts an inner loop, which also an infinite loop. Here the user
user must
must
enter the
enter the string
the string that
string that should
that should match
should match the
match the regular
the regular expression,
regular expression, and
expression, and if
and if it
if itis
it isnot
is not the
not the empty
the empty string
empty string
string
enter
the program creates a Matcher object using the regular expression pattern. For this Matcher
the program creates a Matcher object using the regular expression pattern. For this Matcher
object match is called a method find(), which searches for a substring that matches the
object match is called a method find(), which searches for a substring that matches the
regular
regular expression. As long asasthere is such a substring, ititisisprinted together with its start
regular expression.
expression. As As long
long as there
there isis such
such aa substring,
substring, it is printed
printed together
together with
with itsits start
start
and end
and end index.
end index.
index.
and

I Iwill use the above method to illustrate the syntax of regular expressions, and the meaning
I will
will use
use the
the above
above method
method to
to illustrate
illustrate the
the syntax
syntax of
of regular
regular expressions,
expressions, and
and the
the meaning
meaning
isisthat
thatyou
you should
shouldcontinue
continuewith
with your
yourown
own expressions.
expressions.
is that you should continue with your own expressions.

The
The simplest regular expression isissimply a string and where aasecond string that contains the
The simplest
simplest regular
regular expression
expression is simply
simply aa string
string and
and where
where a second
second string
string that
that contains
contains the
the
first string is matching the expression. Below is an example of a run of the above program:
first string is matching the expression. Below is an example of a run of the above program:

Regular
Regular expression:
expression: Knud
Knud
Search
Search string: Det
string: Det er
er fra
fra Knud
Knud og
og Agnes
Agnes Knudsen
Knudsen Borremose
Borremose
The text "Knud" found
found with start index 11 and end index
with start index 11 and end index 15
15
The
The text "Knud" found with start index 25 and end index
text "Knud" found with start index 25 and end index 29
29
Search string:

That
Thatis,is,
That is,I IIasas
asregular
regularexpression
regular expressionentered
expression entered
entered

Knud
Knud

while
whileI,I,
while I,asas
asaaasearch
searchstring
search stringentered
string entered
entered

Det
Det er
er fra
fra Knud
Knud og
og Agnes
Agnes Knudsen
Knudsen Borremose
Borremose

The
The result
Theresult shows
resultshows that
showsthat the
thatthe search
thesearch string
searchstring contains
stringcontains two
containstwo substrings
twosubstrings that
substringsthat matches
thatmatches the
matchesthe regular
theregular
regular
expression.
expression.
expression.

To
To specifypatterns
Tospecify
specify patternsyou
patterns youneeds
you needsspecial
needs specialcharacters,
special characters,called
characters, calledmeta-characters
called meta-charactersthat
meta-characters thathas
that hasaaaspecial
has special
special
meaning
meaninginin
meaning inaaaregular
regular expression.
regularexpression. There
expression.There are
Thereare following
arefollowing characters:
followingcharacters:
characters:

< (
< ( [
[ {
{ \
\ ^
^ –
– =
= $
$ !
! |
| ]
] }
} )
) ?
? *
* +
+ .
. >
>

Download free eBooks at bookboon.com


24
24
24
24
JAVA 4:
JAVA 4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND COLLECTION
AND COLLECTION CLASSES
CLASSES Strings
strIngs

If there is a need for these characters not to be interpreted, but is perceived as common
characters in the text, you can prefix the character a backslash.

One of the basic patterns are character classes that you define as follows:

- [abc] all characters a, b and c


- [^abc] all characters that is not a, b and c (also called negation)
- [a-zA-Z] all characters from a to z and from A to Z (union)
- [a-d[m-p]] all characters from a to d and m to p (same as [a-dm-p])
- [a-z&&[def]] all characters d, e and f (intersection)
- [a-z&&[^bc]] all characters from a to z but not b and c (set difference)
- [a-z&&[^m-p]] all characters from a to z but not m to p (same as [a-lq-z])

If you, as an example, consider the regurlar expression

[hkr]at

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management [email protected] Follow us on IE MIM Experience

Download free eBooks at bookboon.com


Click on the ad to read more
25
25
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND
AND 4: JAVA’S TYPE
COLLECTION
COLLECTION SYSTEM
CLASSES
CLASSES Strings
strIngs
AND COLLECTION
JAVA 4: JAVA’S TYPECLASSES
SYSTEM strIngs
AND COLLECTION CLASSES strIngs
AND COLLECTION CLASSES strIngs

itit
itmatches
matchesthe
thesubstrings
substringshat,
hat,kat
katand
andrat:
rat:
it matches
matches the
the substrings
substrings hat,
hat, kat
kat and
and rat:
rat:
it matches the substrings hat, kat and rat:
Regular
Regular expression:
expression: [hkr]at
[hkr]at
Regular
Search expression:
string: hat [hkr]at
Regular
Search
Search expression:
string:
string: hat
hat [hkr]at
The text
Search "hat"
string: found with start index 0 and end index 3
The
The text
text
Search "hat" hat
"hat"
string:
found
found with
kat with start
start index
index 0
0 and
and end
end index
index 3
3
The text
Search
Search "hat" kat
string:
string: found with start index
kat 0 and end index 3
The text
Search "kat"
string: found with start index 0 and end index 3
The
The text
text
Search "kat" kat
"kat"
string:
found
found with
rat with start
start index
index 0
0 and
and end
end index
index 3
3
The text
Search
Search "kat" rat
string:
string: found with start index
rat 0 and end index 3
The text
Search "rat"
string: found with start index 0 and end index 3
The
The text
text
Search "rat" rat
"rat"
string:
found
found with
vat with start
start index
index 0
0 and
and end
end index
index 3
3
The text
Search
Search "rat" vat
string:
string: found with start index
vat 0 and end index 3
No match
Search found
string:
No
No match
match
Search found vat
found
string:
No match
Search
Search found it
string:
string: it
it
is
is
is
both
both
both
hat
hat
hat
and
and
and
kat
kat
kat
but
but
but
not
not
not
vat
vat
vatindex
The
The text
Search
text "hat"
string:
"hat" found
it is
found with
both
with start
hat index
and
start kat
index 11
but
11 and
not
and end
vatindex
end 14
14
The
The text
text "hat"
"kat" found
found with
with start
start index
index 11
19 and
and end
end index
index 14
22
The
The text
text "hat"
"kat" found with start index
"kat" found with start index 11
19 and end index
19 and end index 14
22
22
Search
The
Search string:
text "kat" found with start index
string: 19 and end index 22
Search string:
Search string:
As
Asanother
anotherexample,
example,the
thepattern
pattern
As
As another
another example,
example, the
the pattern
pattern
As another example, the pattern
num[^123]
num[^123]
num[^123]
matches all
num[^123]
matches substrings, which consists of the word num followed by aa character which is
matches all substrings,
all substrings, which
which consists
consists of
of the
the word
word num
num followed
followed by
by a character
character which
which is
is
matches
not 1,
matches 2all
or
allsubstrings,
3:
substrings,which
whichconsists
consistsof
ofthe
theword
wordnum
numfollowed
followedby
bya acharacter
characterwhich
whichisis
not
not 1,
1, 22 or
or 3:
3:
not
not1,1,22oror3:3:
Regular
Regular expression:
expression: num[^123]
num[^123]
Regular
Search expression:
string: num num[^123]
Regular
Search
Search expression:
string:
string: num num[^123]
num
No match
Search found
string:
No
No match
match
Search found num
found
string:
No match
Search
Search found num1
string:
string: num1
num1
No
No match
Search found
string:
match found num1
No match
Search found
string:
No match
Search
Search found num4
string:
string: num4
num4
The
The text
Search "num4"
string:
text "num4" found
num4
found with
with start
start index
index 0
0 and
and end
end index
index 4
4
The text
Search "num4"
string: found with start index 0 and end index 4
The text
Search "num4"
string:
Search string: found with start index 0 and end index 4
Search string:
The
The regular expression
The regular
regular expression
expression
The
The regularexpression
regular expression
[A-G]
[A-G]
[A-G]
[A-G]
matches
matchesall
alluppercase
uppercaseletters
lettersfrom
fromAAtotoG:
G:
matches
matches all uppercase letters from A
all uppercase letters from A to
to G:
G:
matches all uppercase letters from A to G:
Regular
Regular expression:
expression: [A-G]
[A-G]
Regular
Search expression:
string: Anders[A-G]
Andersen
Regular
Search
Search expression:
string:
string: Anders
Anders[A-G]
Andersen
Andersen
The
The text
Search
text "A"
string:
"A" found with
Anders
found start
Andersen
with start index
index 0
0 and
and end
end index
index 1
1
The
The text
text "A"
"A" found
found with
with start
start index
index 0
7 and
and end
end index
index 1
8
The
The text
text "A" found
"A" found with
with start
start index
index 0
7
7 and
and end
end index
index 1
8
8
Search
The
Search string:
text
string: Harald
"A" found
Harald Hen
with start index
Hen 7 and end index 8
Search
No string:
match found Harald Hen
Search
No
No string:
match
match found Harald
found Hen
Search
No string:
match
Search found
string: Harald
Harald Gormssøn
Gormssøn
Search
The string:
text "G" Harald
found Gormssøn
with start index 7 and end index 8
Search
The
The string:
text
text "G" Harald
found
"G" found withGormssøn
with start
start index
index 7
7 and
and end
end index
index 8
8
Search
The
Search string:
text "G" found with start index
string: 7 and end index 8
Search string:
Search string:

Download free eBooks at bookboon.com


2626
26
26
JAVA
JAVA4: JAVA’S TYPE SYSTEM
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION CLASSES Strings
AND COLLECTION CLASSES
COLLECTION CLASSES strIngs
strIngs

The
Thepattern
The pattern
pattern

[^0-9]
[^0-9]

matches
matchesany character that isisnot a digit:
matches any
any character
character that
that is not
not aa digit:
digit:

Regular
Regular expression:
expression: [^0-9]
[^0-9]
Search string: abc
Search string: abc
The
The text
text "a"
"a" found
found with
with start
start index
index 0
0 and
and end
end index
index 1
1
The
The text "b" found with start
text "b" found with start index
index 1
1 and
and end
end index
index 2
2
The
The text
text "c"
"c" found
found with
with start
start index
index 2
2 and
and end
end index
index 3
3
Search string: 0x123
Search string: 0x123
The
The text
text "x"
"x" found
found with
with start
start index
index 1
1 and
and end
end index
index 2
2
Search string: 1234
Search string: 1234
No
No match
match found
found
Search string:
Search string:

The
The following expression is an example ofofaaunion that matches all digits and lowercase
The following
following expression
expression is
is an
an example
example of a union
union that
that matches
matches all
all digits
digits and
and lowercase
lowercase
letters
lettersbetween a and f:
letters between
between aa and
and f:
f:

Regular
Regular expression:
expression: [0-9[a-f]]
[0-9[a-f]]
Search string: xya1z
Search string: xya1z
The
The text
text "a"
"a" found
found with
with start
start index
index 2
2 and
and end
end index
index 3
3
The
The text "1" found with start index
text "1" found with start index 3
3 and
and end
end index
index 4
4
Search
Search string:
string: xyz
xyz
No
No match
match found
found
Search
Search string:
string:

Below
Below
Belowisis
isan
anexample
an exampleofof
example ofan
anintersection.
an intersection.The
intersection. Thegoal
The goalisis
goal istoto
toshow
showthe
show thesyntax,
the syntax,for
syntax, forthe
for theregular
the regular
regular
expression
expression could
couldinstead
insteadbe
bewriten
writenas
as[h-n].
[h-n].
expression could instead be writen as [h-n].

Regular
Regular expression:
expression: [a-n&&[h-u]]
[a-n&&[h-u]]
Search
Search string: Preben
string: Preben
The
The text
text "n"
"n" found
found with
with start index 5
start index and end
5 and end index
index 6
6
Search string: Frede
Search string: Frede
No
No match
match found
found
Search
Search string:
string:

Some specific
Somespecific
Some character
specificcharacter classes
characterclasses can
classescan be
canbe identified
beidentified by
byaaasymbol:
identifiedby symbol:
symbol:

- . Any character
--- .. Anycharacter
Any character
----
10
\d\d The
\d The
The10 digits
10digits
digits
---- \D All
\D All characters
Allcharacters that
charactersthat not
thatnot are
areaaadigit
notare digit
digit
\D

Download free eBooks at bookboon.com


2727
27
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA
AND4:4:JAVA’S
JAVA’STYPE
COLLECTIONTYPE SYSTEM
SYSTEM
CLASSES strIngs
ANDCOLLECTION
AND COLLECTIONCLASSES
CLASSES strIngs
Strings

- \s A whitespace: [ \t\n\f\r]
--- \s\s AAwhitespace:
whitespace:[ [\t\n\f\r]
\t\n\f\r]
- \S All characters that not are a whitespace
--- \S\S Allcharacters
All charactersthat
thatnot
notarearea awhitespace
whitespace
- \w Lettes and digits: [a-zA-Z0-9]
--- \w\w Lettesand
Lettes anddigits:
digits:[a-zA-Z0-9]
[a-zA-Z0-9]
- \W All other characters: [^\w]
--- \W\W Allother
All othercharacters:
characters:[^\w]
[^\w]

Example of a regular expression, which is a dot:


Exampleofofa aregular
Example regularexpression,
expression,which
whichisisa adot:
dot:
Regular expression: .
Regular expression: .
Search string: 123
Search string: 123
The text "1" found with start index 0 and end index 1
The text "1" found with start index 0 and end index 1
The text "2" found with start index 1 and end index 2
The text "2" found with start index 1 and end index 2
The text "3" found with start index 2 and end index 3
The text "3" found with start index 2 and end index 3
Search string:
Search string:

Example
Exampleofofa aregular
regularexpression,
expression,which
whichmatches
matchesa adigit:
digit:
Example of a regular expression, which matches a digit:
Regular expression: \d
Regular expression: \d
Search string: ab12cd
Search string: ab12cd
The text "1" found with start index 2 and end index 3
The text "1" found with start index 2 and end index 3
The text "2" found with start index 3 and end index 4
The text "2" found with start index 3 and end index 4
Search string:
Search string:

Download free eBooks at bookboon.com


28 Click on the ad to read more
2828
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Strings
AND COLLECTION CLASSES strIngs

Example
Exampleofofa aregular
regularexpression,
expression,which
whichisisa awhitespace:
whitespace:

Regular expression: \s
Search string: 1 2 3
The text " " found with start index 1 and end index 2
The text " " found with start index 3 and end index 4
Search string:

Thereare
There arealso
alsosome
someoptions
optionstotospecify
specifythat
thata apattern
patternmust
mustoccur
occurseveral
severaltimes
timesand
andfor
foreach
each
thereare
there areeven
eventhree
threevariants.
variants.IfIfXXrepresents
representsa apattern
patternthe
thesyntax
syntaxisis

X?
X? X??
X?? X?+
X?+ occursonce
XXoccurs onceorornot
notatatallall

X*X* X*?
X*? X*+
X*+ XXoccurs
occursseveral
severaltimes
timesororpossibly
possiblynot
notatatallall

X+
X+ X+?
X+? X++
X++ XXoccurs
occursatatleast
leastonce
once

X{n}
X{n} X{n}?
X{n}? X{n}+
X{n}+ XXoccurs
occursexactly
exactlyn ntime
time

X{n,}
X{n,} X{n,}?
X{n,}? X{n,}+
X{n,}+ XXoccurs
occursatatleast
leastn ntime
time

X{n,m}
X{n,m} X{n,m}?
X{n,m}? X{n,m}+
X{n,m}+ XXoccurs
occursatatleast
leastn ntimes
timesand
andatatmost
mostmmtimes
times

InInprinciple,
principle,these operatorsare
theseoperators aresimple
simpleenough,
enough,but
butititisisnot
notalways
alwayssosoeasy
easytotopredict
predict
theoutcome:
the outcome:

Regular expression: a?
Search string: 123
The text "" found with start index 0 and end index 0
The text "" found with start index 1 and end index 1
The text "" found with start index 2 and end index 2
The text "" found with start index 3 and end index 3
Search string:

a?a?matches
matchesa asubstring
substringconsisting
consistingofofzero
zeroororone
onecharacter
charactera.a.IfIfx xdenotes
denotesthis
thispattern,
pattern,one
one
can
canperceive
perceivethe
thesearch
searchstring
string123
123asasx1x2x3x,
x1x2x3x,and
andyou
youwill
willtherefore
thereforehave
have44matches.
matches.
Therefore,
Therefore,the
thefollowing
followingpattern
patternresults
resultsinin66matches:
matches:

Regular expression: a?
Search string: 1a2a3
The text "" found with start index 0 and end index 0
The text "a" found with start index 1 and end index 2
The text "" found with start index 2 and end index 2
The text "a" found with start index 3 and end index 4
The text "" found with start index 4 and end index 4
The text "" found with start index 5 and end index 5
Search string:

Download free eBooks at bookboon.com


29
29
JAVA
JAVA4:4:
JAVA 4:JAVA’S
JAVA’STYPE
JAVA’S TYPESYSTEM
TYPE SYSTEM
SYSTEM
AND
ANDCOLLECTION
JAVA
AND COLLECTION CLASSES
4: JAVA’S TYPE
COLLECTION CLASSES
SYSTEM
CLASSES Strings
strIngs
strIngs
AND COLLECTION CLASSES strIngs

a*a*matches
matchesany
anynumber
numberofofthe
thecharacter
charactera,a,sosoyou
youend
endwith
with55matches:
matches:
a* matches any number of the character a, so you end with 5 matches:
Regulært udtryk: a*
Regulært udtryk:
Søgestreng: a*
12aaaaaaaaaaaa3
Søgestreng: 12aaaaaaaaaaaa3
Teksten "" fundet med start på indeks 0 og slut på indeks 0
Teksten
Teksten ""
"" fundet
fundet med
med start
start på
på indeks
indeks 01 og
og slut
slut på
på indeks
indeks 01
Teksten
Teksten "aaaaaaaaaaaa" fundet med start på indeks 2 og slut1 på indeks 14
"" fundet med start på indeks 1 og slut på indeks
Teksten
Teksten "aaaaaaaaaaaa" fundetpåmed
"" fundet med start start14påogindeks
indeks slut på2 og slut 14
indeks på indeks 14
Teksten "" fundet med start på indeks 14 og slut på indeks
Teksten "" fundet med start på indeks 15 og slut på indeks 15 14
Teksten "" fundet med start på indeks 15 og slut på indeks 15

Asa+
As a+requires
requiresatatleast
leastone
onecharacter
charactera,a,you
youbelow
belowget
getrespectively
respectivelyno
noand
and11match:
match:
As a+ requires at least one character a, you below get respectively no and 1 match:
Regular expression: a+
Regular expression:
Search string: 123 a+
Search
No match found 123
string:
No match
Search found 123aaa45
string:
Search
The text "aaa" 123aaa45
string: found with start index 3 and end index 6
The
Search string: found with start index 3 and end index 6
text "aaa"
Search string:

The above examples show how the method find() in the class Matcher works. It searches over
The
The above examples show
showhow the method find()
find()ininthe class Matcher works. ItItsearches
searchesover
againabove examples
in the search string how
untilthe
it method
finds a substring the
thatclass Matcher
matches theworks. over
regular expression. If
again
again in the search string until it finds a substring that matches the regular expression.IfIf
in the search string until it finds a substring that matches the regular expression.
it finds a match, the index has reached the first character after the string. The next search
ititfinds
findsaamatch,
match,the
theindex
indexhas
hasreached
reachedthe thefirst
firstcharacter
characterafter
afterthe
thestring.
string.The
Thenext
nextsearch
search
will start from that location. Consider again a search similar to the above:
will
willstart
startfrom
fromthat
thatlocation.
location.Consider
Consideragainagainaasearch
searchsimilar
similartotothe
theabove:
above:
Regular expression: a?
Regular expression:
Search string: aaa a?
Search
The textstring: aaa with start index 0 and end index 1
"a" found
The
The text "a" found with
text "a" found with start
start index
index 01 and
and end
end index
index 12
The
The text "a" found with start index 2 and end index 2
text "a" found with start index 1 and end index 3
The
The text
text "a" found with
"" found with start
start index
index 32 and
and end
end index
index 33
The text
Search "" found with start index 3 and end index 3
string:
Search string:

1. The search starts from the begining, and the index is 0. The search ends when the
1.1.The
The search starts
startsfrom the
thebegining, and
andthe index isis0.0.The
Thesearch
searchends
endswhen
whenthe
indexsearch
is 1 when fromsubstring
the begining,
“a” matches thetheindex
regular expression. the
index
indexisis11when
whenthe thesubstring
substring“a”“a”matches
matchesthe theregular
regularexpression.
expression.
2. Next search stops with the index in place 2, where they have found the next
2.2.Next
Next search
search stops
stops with
with the
the index
index inin place
place 2,2, where
where they they have
have found
found thethe next
next
substring “a” that matches.
substring “a” that matches.
3. substring
The third “a” thatfinds
search matches.
the substring “a” and stop index of 3.
3.3.The
The third
third search
search finds
findsthe
thesubstring
substring “a” and stop index ofof3.3.
4. Finally stops the last search when the“a” endand
of stop indexis
the string reached, and at that time
4.4.Finally
Finallystops
stopsthe
thelast
lastsearch
searchwhen
whenthetheend
endofofthethestring
stringisisreached,
reached,and andatatthat
thattime
time
the index is still 3 and you have found the empty string that matches the regular
the
theindex
indexisisstill
still33and
andyou
youhave
havefound
foundthetheempty
emptystring
stringthat
thatmatches
matchesthetheregular
regular
expression.
expression.
expression.

Download free eBooks at bookboon.com


3030
30
30
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Strings
strIngs

Below
Belowisisananexample
examplethat
thatshows
showsa abit
bitofofthe
thesame,
same,but
butthe
thefirst
firstsearch
searchstops
stopsfirst
firstwhen
whenthe
the
index
indexisis3:3:

Regular expression: a*
Search string: aaa
The text "aaa" found with start index 0 and end index 3
The text "" found with start index 3 and end index 3
Search string:

This
Thisalso
alsoapplies
appliestotothe
theexample
examplebelow,
below,but
butthe
thelast
lastsearch,
search,which
whichresults
resultsininthe
theempty
emptystring
string
does not match the regular expression:
does not match the regular expression:

Regular expression: a+
Search string: aaa
The text "aaa" found with start index 0 and end index 3
Search string:

The
Theabove
aboveexamples
examplesshow
showthat
thatyou
youoften
oftenget
geta adifferent
differentresult
resultthan
thanexpected.
expected.If,If,for
forexample
example
you
you want an expression that matches certain number of characters, the syntax oftenwill
want an expression that matches certain number of characters, the syntax often willbebe
something
somethinglike
likethe
thefollowing:
following:

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

Download free eBooks at bookboon.com


Click on the ad to read more
3131
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA 4:
4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S
JAVA’S TYPE
COLLECTION TYPE SYSTEM
SYSTEM
CLASSES Strings
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES strIngs
strIngs
AND COLLECTION CLASSES strIngs

Regular
Regular expression:
Regular expression: a{3}
expression: a{3}
a{3}
Search
Search string:
string: aaaaa
aaaaa
Search string: aaaaa
The
The text
The text "aaa"
text "aaa" found
"aaa" found with
found with start index
with start
start index 0 and
index 0
0 and end index
and end
end index 3
index 3
3
Search string:
Search string:

IfIf you
Ifyou want
wanttoto
youwant search
searchaaagroup
tosearch group
groupofof characters
ofcharacters used
charactersused parentheses,
usedparentheses, where
parentheses,where the
wherethe following
thefollowing expression
followingexpression
expression
matches
matches sekvenses
matchessekvenses 123123:
sekvenses123123:
123123:

Regular
Regular expression:
Regular expression: (123){2}
expression: (123){2}
(123){2}
Search
Search string:
Search string: 891231234512367
string: 891231234512367
891231234512367
The
The text "123123" found
text "123123" found with
found with start
with start index 2
start index
index 2 and end
2 and
and end index 8
end index
index 8
8
Search
Search string:
Search string:
string:

As
Asanother
As anotherexample,
another example,the
example, thefollowing
the followingpattern
following patternmatches
pattern matches33
matches 3ofof
ofthe
thecharacters
the charactersa,a,
characters a,bbband
andc:c:
and c:

Regular
Regular expression:
Regular expression: [abc]{3}
expression: [abc]{3}
[abc]{3}
Search
Search string:
string: abdbbbeabccbaf
abdbbbeabccbaf
Search string: abdbbbeabccbaf
The
The text "bbb" found
text "bbb" found with
found with start
with start
start index
index
index 3
3 and
3 and end
and end index
end index 6
index 6
6
The
The text "abc" found with start
text "abc" found with start index
index
index 7
7 and end index 10
7 and
and end
end index
index 10
10
The
The text
text "cba"
"cba" found
found with
with start
start index
index
index 10 and
10 and end
and end index
index 13
end index 13
13
Search string:
Search string:

As
As shown
showninin
Asshown the
inthe table
thetable above
tableabove there
abovethere are
thereare three
arethree options
threeoptions
optionsforfor specifying
forspecifying quantifiers.
specifyingquantifiers.
quantifiers.AsAs mentioned
Asmentioned
mentioned
the
the search in the search string moves the index until a match is found. If the quantifiersinin
the search
search inin the
the search
search string
string moves
moves the
the index
index until
until a a match
match is
is found.
found. If
If the
the quantifiers
quantifiers in
the
the first
first column
column are
are used
used the
the index
index isis moved
moved as
as far
far as
as possible.
possible. AA dot
dot means
means
the first column are used the index is moved as far as possible. A dot means the character the
the character
character
class
classconsisting
consistingofofall allcharacters,
characters,and
andthethepattern
pattern

.*abc
.*abc
.*abc

therefore
therefore means
means00
thereforemeans 0oror more
ormore characters
morecharacters followed
charactersfollowed
followedbyby abc.
byabc.
abc.AsAs the
Asthe index
theindex moved
movedasas
indexmoved far
fartoto
asfar the
tothe
the
right
rightasaspossible
possiblethe
theresult
resultofofthe
thefollowing
followingsearch
searchisisonly
onlyininone
onematch:
match:

Regular
Regular expression:
Regular expression: .*abc
expression: .*abc
.*abc
Search
Search string:
string: xabcxxxxxabc
xabcxxxxxabc
Search string: xabcxxxxxabc
The
The text "xabcxxxxxabc" found
text "xabcxxxxxabc" found with start
found with
with start index 0
start index
index 0 and end
0 and
and end index 12
end index
index 12
12
Search string:
Search string:

IfIfthe quantifiers ininthe second column are used, the search stops asassoon as aamatch is
If the
the quantifiers
quantifiers in the
the second
second column
column are
are used,
used, the
the search
search stops
stops as soon
soon as
as a match
match is
is
found.
found. Therefore
Therefore results
resultsthe
the following
followingsearch
searchtwo
two matches:
matches:
found. Therefore results the following search two matches:

Regular
Regular expression:
Regular expression: .*?abc
expression: .*?abc
.*?abc
Search
Search string:
Search string: xabcxxxxxabc
string: xabcxxxxxabc
xabcxxxxxabc
The
The text "xabc" found
text "xabc" found with
found with start
with start index
start index 0
index 0 and
0 and
and end
end
end index
index 4
index 4
4
The text "xxxxxabc" found with start index
index 4
The text "xxxxxabc" found with start index 4
4 and
and
and end
end index
index 12
end index 12
12
Search string:
Search string:

Download free eBooks at bookboon.com


32
32
32
32
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Strings
strIngs
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES strIngs
Finally
Finallyififthe
thequantifiers
quantifiersininthe
thethird
thirdcolumn
columnare
areused,
used,the
theindex
indexisismoved
movedasasfar
farasaspossible.
possible.
Because
Because .* matches all characters, the index is moved to the end of the string – andpast
.* matches all characters, the index is moved to the end of the string – and past
Finally
abc. if the quantifiers
Therefore, the in the
following thirdhas
search column
no are used, the index is moved as far as possible.
match:
abc. Therefore, the following search has no match:
Because .* matches all characters, the index is moved to the end of the string – and past
abc. Therefore,
Regular the following
expression: .*+abc search has no match:
Search string: xabcxxxxxabc
Regular
No matchexpression:
found .*+abc
Search string: xabcxxxxxabc
No match found
Search string:
There are also some options to specify where in the search string a match must occur:

There
Therearearealso
alsosome
someoptions
optionstotospecify
specifywhere
whereininthe
thesearch
searchstring
stringaamatch
matchmust
mustoccur:
occur:
- ^ the start of the line
- $ the end of the line
--- ^^ the thestart
startofofthe
theline
line
- \b the start of a word
--- $$ the theend
endofofthe
theline
line
- \B not in the start of a word
--- \b\b the thestart
startofofaaword
word
- \A the start of the search string
--- \B\B not notininthe
thestart
startofofaaword
word
- \G the start of the previous match
--- \A\A the start of the searchstring
the start of the search string
- \z the start of the search string
--- \G\G the thestart
startofofthe
theprevious
previousmatch
match
--- \z\z the thestart
startofofthe
thesearch
searchstring
string
Correspondingly, the following searches results in a single match:

Correspondingly,
Correspondingly,the
thefollowing
followingsearches results in a single match:
Regular expression: ^abc searches results in a single match:
Search string: abcabcabc
Regular
The textexpression:
"abc" found^abc
with start index 0 and end index 3
Search string: abcabcabc
The textexpression:
Regular "abc" foundabc$
with start index 0 and end index 3
Search string: abcabcabc
Regular
The textexpression:
"abc" foundabc$
with start index 6 and end index 9
Search string: abcabcabc
The text "abc" found with start index 6 and end index 9
Search string:
The above examples demonstrate the basics regarding regular expressions, but there are
several options, and the classes Pattern and Matcher also has other useful methods. Here I
The above examples demonstrate the basics regarding regular expressions, but there are
The
referabove
to theexamples demonstrate
documentation, the basics
and will insteadregarding
end this regular expressions,
introduction but expressions
to regular there are
several options, and the classes Pattern and Matcher also has other useful methods. Here I
several
with aoptions, and the classes Pattern and Matcher also has other useful methods. Here I
few examples.
refer to the documentation, and will instead end this introduction to regular expressions
refer to the documentation, and will instead end this introduction to regular expressions
with a few examples.
with a few
In Java, theexamples.
name of a variable start with a letter, and then there should follow any number
of characters consisting of letters, digits and the character _. In addition, it is recommended
In Java, the name of a variable start with a letter, and then there should follow any number
Inthat
Java, the name
a variable of a always
name variablestarts
start with
with aa lowercase
letter, andletter.
then there
If oneshould follow
decides that any number
it’s the rules,
of characters consisting of letters, digits and the character _. In addition, it is recommended
ofa characters
variable is consisting
defined byofusing
letters,
thedigits and the
following character
regular _. In addition, it is recommended
expressions:
that a variable name always starts with a lowercase letter. If one decides that it’s the rules,
that a variable name always starts with a lowercase letter. If one decides that it’s the rules,
a variable is defined by using the following regular expressions:
a variable is defined by using the following regular expressions:

Download free eBooks at bookboon.com


33
33
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
JAVA
AND 4: JAVA’S
4: JAVA’S TYPE
TYPE SYSTEM
SYSTEM
CLASSES Strings
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES strIngs
strIngs

private
private static
static void
void test05()
test05()
{
{
Pattern
Pattern pattern
pattern =
= Pattern.compile("^[a-z]+[a-zA-Z_0-9]*$");
Pattern.compile("^[a-z]+[a-zA-Z_0-9]*$");
for (String
for (String str
str =
= enter("?
enter("? ");
"); str.length()
str.length() >
> 0;
0; str
str =
= enter("?
enter("? "))
"))
{
{
Matcher matcher
Matcher matcher == pattern.matcher(str);
pattern.matcher(str);
System.out.println(matcher.find());
System.out.println(matcher.find());
}
}
}
}

IfIfyou
youexecutes
executesthe
themethod,
method,you
youcan
canenter
enterstrings,
strings,and
andthe
themethod
methodwill
willvalidate
validatewhere
wherethe
the
string
stringisisaavalid
validvariable.
variable.The
Thepattern
patternsays
saysthat
thatthe
thestring
stringmust
muststart
startwith
withjust
justaasmall
smallletter:
letter:

[a-z]+
[a-z]+

Next,
Next,the
thestrings
stringsmust
mustend
endwith
withany
anynumber
numberofofcharacters
charactersthat
thatare
areletters,
letters,digits
digitsor
or_:_:

[a-zA-Z_0-9]*$
[a-zA-Z_0-9]*$

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

Download free eBooks at bookboon.com


Click on the ad to read more
34
34
34
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Strings
strIngs

Similarly,
Similarly,the
thefollowing
followingmethod
methodvalidates
validateswhether
whetheraastring
stringrepresents
representsaabinary
binarynumber
number(a(a
string
stringconsisting
consistingofof00and
and1):
1):

private static void test06()


{
Pattern pattern = Pattern.compile("^[01][01]*$");
for (String str = enter("? "); str.length() > 0; str = enter("? "))
{
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.find());
}
}

As
Asaacomplex
complexexample
exampleisisshown
shownaamethod
methodusing
usingaaregular
regularexpression
expressiontotovalidate
validatean
anemail
email
address. Note that I have already used the method in the book Java 3.
address. Note that I have already used the method in the book Java 3.

public static boolean isMail(String mail)


{
return Pattern.compile(
"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.
[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$").
matcher(mail).matches();
}

ItItisisaavery
verycomplex
complexexpressions,
expressions,and
andalso
alsoitituses
usesrules
rulesand
andoperators
operatorsthat
thatI Inot
nothave
havehighlighted
highlighted
above, so I will try to explain the expression. It starts with a character
above, so I will try to explain the expression. It starts with a character class: class:

[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+

ItItdefines
definesthe
thesmall
smalland
andcapital
capitalletters,
letters,digits
digitsand
andaanumber
numberofofother
otherspecial
specialcharacters.
characters.YouYou
should note that when a special character is defined in a character class, it
should note that when a special character is defined in a character class, it is unnecessary is unnecessary
totoescape
escapethemthemwith
withaabackslash.
backslash.The Theexception
exceptionisis[,[,] ]and
and––because
becausethese
thesecharacters
charactersare
are
used to define the class. An email address consists of two parts separated by the
used to define the class. An email address consists of two parts separated by the @ character, @ character,
asaswe
wecall
callrespectively
respectivelythe
thefirst
firstname
nameand andthethelast
lastname.
name.The
Theabove
abovecharacter
characterclass
classdefines
defines
thus
thus what characters the first name may consist of, and that there must be at least oneofof
what characters the first name may consist of, and that there must be at least one
these
thesecharacters.
characters.YouYoushould
shouldnote notethat
thatthe
theclass
classallows
allowsmany
manyother
othercharacters
charactersthanthanwhat
whatisis
usual
usualininmail
mailaddresses,
addresses,but
butthey
theyare
areactually
actuallylegal
legal––atatleast
leastififyou
youincludes
includesmail
mailaddresses
addresses
from
fromallallcountries.
countries.

After
After the
the above
above character
character class
class follows
follows the
the separator
separator @,
@, and
and then
then the
the last
last name
name that
that isis
made
madeup upofoftwo
twoterms,
terms,sosothat
thataastring
stringshould
shouldmatch
matchthetheone
oneororthe
theother.
other.YouYoudefine
definethis
this
selection with the character |, and the first expression is therefore:
selection with the character |, and the first expression is therefore:

(\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])

Download free eBooks at bookboon.com


3535
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
JAVA CLASSES
4: JAVA’S TYPE SYSTEM strIngs
AND
JAVA COLLECTION CLASSES
4: JAVA’S TYPE SYSTEM strIngs
AND COLLECTION CLASSES Strings
AND COLLECTION CLASSES strIngs

The
The expression
expression matches
matches aa bracket
bracket begin,
begin, four
four integer
integer of
of at
at least
least 1
1 and
and no
no more
more than
than 3
3 digits
digits
The
The expression
expression
separated of a matches
matches
dot, and a
a bracket
bracket
last a begin,
begin,
final four
four
bracket. integer
integer
This of
of
means at
at least
least
that 1
1
the and
and no
no more
more
expression than
than 3
3
matches digits
digits
an IP
separated of a dot, and last a final bracket. This means that the expression matches an IP
separated
separated of a dot, and last a final bracket. This means that the expression matches an IP
address in ofbrackets.
address in a dot, and last a final bracket. This means that the expression matches an IP
brackets.
address in brackets.
address in brackets.
The
The second
second expression
expression has
has the
the form:
form:
The
The second expression has the form:
second expression has the form:
(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,})
(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,})
(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,})
Here
Here is
is
Here
Here is
is
[a-zA-Z\\-0-9]+
[a-zA-Z\\-0-9]+
[a-zA-Z\\-0-9]+
a character class that matches uppercase and lowercase letters, a hyphen and digits, and
a character class that matches uppercase and lowercase letters, a hyphen and digits, and
there
athere must be
character at that
class least one of these characters. Next, follow a dot. Of these
andgroups
digits,must
must be at least matches uppercase
one of these and lowercase
characters. letters,
Next, follow a hyphen
a dot. Of these groups and
must
be at least
there mustone:
be at least one of these characters. Next, follow a dot. Of these groups must
be at least one:
be at least one:
([a-zA-Z\\-0-9]+\\.)+
([a-zA-Z\\-0-9]+\\.)+
([a-zA-Z\\-0-9]+\\.)+
Finally
Finally there
there must
must be
be at
at least
least two
two letters.
letters. The
The result
result is
is that
that the
the last
last name
name is
is either
either an
an IP
IP
address
Finally or a
there server
must name.
be at The
least entire
two expression
letters. The is surrounded
result is that theby the
last characters
address or a server name. The entire expression is surrounded by the characters ^ and IP
name is ^
either and
an $,
$,
which
address means
or a that
serverthere
name.must
The be no
entirefront or behind
expression is the expression.
surrounded
which means that there must be no front or behind the expression. by the characters ^ and $,
which means that there must be no front or behind the expression.
EXERCISE
EXERCISE 2 2
EXERCISE
In 2
In this
this exercise,
exercise, you
you should
should extends
extends the
the class
class library
library PaLib.
PaLib. Add
Add the
the method
method isMail()
isMail() to
to
the
In class
the this Str.
Str. You
classexercise, must
Youyou also
also add
mustshould the
the following
extends
add the class methods
following when
when they
library PaLib.
methods they should
Add be
be implemented
the method
should isMail() to
implemented
using
the
using aa regular
class expression:
Str. You
regular must also add the following methods when they should be implemented
expression:
using a regular expression:
/**
/**
* Validates where
/** a string is hexadecimal integer without sign, when the syntax
* Validates where a string is hexadecimal integer without sign, when the syntax
* Validates
* should be that aofstring
Java, where the numbers
integerstarts with 0x.when the syntax
* should bewhere
that of Java,iswhere
hexadecimal
the numbers without
starts sign,
with 0x.
*
* @param
should str
be The
that string
of Java,to be validated
where the numbers starts with 0x.
* @param str The string to be validated
* @return
* @return true,
@param str if
Theif str
string represents hexadecimal
to be validated integer without sign
* true, str represents hexadecimal integer without sign
*/
*
*/ @return true, if str represents hexadecimal integer without sign
public
*/ static boolean isHex(String str) { … }
public static boolean isHex(String str) { … }
public static boolean isHex(String str) { … }
/**
/**
* Validates whether a string is a long when the number must either be 0, or an
/**
* Validates whether a string is a long when the number must either be 0, or an
* Validates
* integer which maya have
whether stringa is
sign and must
a long not number
when the start with 0, but be
must either otherwise
0, or an
* integer which may have a sign and must not start with 0, but otherwise
* have
* have maximum
integer 17
which 17maydigits.
have a sign and must not start with 0, but otherwise
* maximum digits.
* have
* @param str The
maximum 17 string
digits.to be validated
* @param str The string to be validated
* @return
* @return true,
@param str if
Theif str
string represents a long
to be validated
* true, str represents a long
*/
* @return true, if str represents a long
*/
public
*/ static boolean isLong(String str) { … }
public static boolean isLong(String str) { … }
public static boolean isLong(String str) { … }

Download free eBooks


36 at bookboon.com
36
36
36
JAVA 4: JAVA’S TYPE SYSTEM
JAVA COLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Strings
AND COLLECTION CLASSES strIngs

/**
* Validates where a string is a double when the number may start with a sign and
* there must be a decimal point followed by at least one digit. Moreover, it
* should be possible to end the number with a eksponent part.
* @param str The string to be validated
* @return true, if str represents a double
*/
public static boolean isDouble(String str) { … }

Also,
Also, write
write aa test
test program
program RegProgram
RegProgram that
that can
can test
test the
the new
new methods
methods in
in the
the class
class library.
library.

Download free eBooks at bookboon.com


Click on the ad to read more
37
37
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Inner classes

JAVA 4: JAVA’S TYPE SYSTEM


JAVA 4: JAVA’S TYPE SYSTEM

4 INNER CLASSES
AND COLLECTION CLASSES Inner Classes
AND COLLECTION CLASSES Inner Classes

4
4Java, youINNER
In can use nested CLASSES
INNER CLASSES
classes that are classes within classes, and you can in fact can even
define a class inside a method. In most cases defines a class a thing or a concept concerning
the program’s
In Java, you canproblem area,classes
use nested and allthat
thatareis classes
said about
withinclasses into
classes, this
and youplace stillfact
can in apply, but
can even
In Java, you can use nested classes that are classes within classes, and you can in fact can even
sometimes youinside
define a class need asmall classes
method. Inonly
mosttocases
be used
definesinternally
a class ainthing
a another class, and
or a concept in such
concerning
define a class inside a method. In most cases defines a class a thing or a concept concerning
cases you can define
the program’s probleman area,
innerand
class.
all Seen
that isfromsaid the finished
about classesprogram
into thisitplace
playsstill
no apply,
role, and
but
the program’s problem area, and all that is said about classes into this place still apply, but
the programyou
sometimes is no more
need or less
small effective
classes only toforbethat,
usedbut you get in
internally a better encapsulation,
a another class, and in which
such
sometimes you need small classes only to be used internally in a another class, and in such
incases
turnyou
cancan
result in code
define that is
an inner easier
class. to read
Seen from andthe understand.
finished program it plays no role, and
cases you can define an inner class. Seen from the finished program it plays no role, and
the program is no more or less effective for that, but you get a better encapsulation, which
the program is no more or less effective for that, but you get a better encapsulation, which
Itinsounds
turn cansimple
resulttoindefine inneris classes,
code that easier toand readit and
also understand.
is, but there is nevertheless a lot of
in turn can result in code that is easier to read and understand.
details that you needs to know, and that’s what this chapter covers. Basically, you can define
classes as follows:
It sounds simple to define inner classes, and it also is, but there is nevertheless a lot of
It sounds simple to define inner classes, and it also is, but there is nevertheless a lot of
details that you needs to know, and that’s what this chapter covers. Basically, you can define
details that you needs to know, and that’s what this chapter covers. Basically, you can define
classes as follows:
classes as follows:

class OuterClass
class OuterClass
{
{


static class NestedClass
static class NestedClass
{
{


}
}
class InnerClass
class InnerClass
{
{


}
}
}
}

where
wherethe theclass
classOuterClass
OuterClasshas hastwo
twoinner
innerclasses.
classes.The
Thedifference
differenceisisthat
thatone
oneisisstatic,
static,while
while
where the class OuterClass has two inner classes. The difference is that one is static, while
the
theother
otherisisnot.
not.AAstatic
staticinner
innerclasses
classesareareusually
usuallycalled
calledaanested
nestedclass,
class,while
whileaanonnonstatic
staticisis
the other is not. A static inner classes are usually called a nested class, while a non static is
called
calledan aninner
innerclass.
class.An
Aninner
innerclass
classcancanrefer
refertotoall
allininthe
theouter
outerclass
classregardless
regardlessofofwhether
whether
called an inner class. An inner class can refer to all in the outer class regardless of whether
ititisisprivate
privateor ornot.
not.AAnested,
nested,ininturn,
turn,can cannot
notrefer
refertotothe
theinstance
instancevariables
variablesorornon-static
non-static
it is private or not. A nested, in turn, can not refer to the instance variables or non-static
methods
methods inin the the outer
outer class,
class, unless
unless itit has
has an
an object.
object. Similar
Similar toto other
other static
static members
members inin aa
methods in the outer class, unless it has an object. Similar to other static members in a
class,
class,references
referencestotoaanested
nestedclass
classmust
mustbe bedone
doneviaviathe
thename
nameofofthe theouter
outerclass,
class,for
forexample
example
class, references to a nested class must be done via the name of the outer class, for example
something
somethinglike likethe
thefollowing:
following:
something like the following:

OuterClass.NestedClass obj = new OuterClass.NestedClass();


OuterClass.NestedClass obj = new OuterClass.NestedClass();

Download free eBooks at bookboon.com


38
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Inner classes
AND COLLECTION CLASSES Inner Classes

An
Aninner
innerclass
classisisininthe
thesame
sameway wayasasother
othermembers
membersofofthetheouter
outerclass
classassociated
associatedwith
withanan
object
objectofofthe
theouter
outerclass,
class,and
andthisthismeans,
means,that thatananinner
innerclass
classcan
cannot
nothave
havestatic
staticmembers.
members.
Stated
Stated slightly differently, objects that are instances of an inner class, only existsininanan
slightly differently, objects that are instances of an inner class, only exists
instance
instanceofofthe
theouter
outerclass.
class.IfIfouter
outerisisananobject
objectofoftype
typeOuterClass,
OuterClass,you
youcan
cancreate
createananobject
object
ofofthe type InnerClass as follows:
the type InnerClass as follows:

OuterClass.InnerClass obj = outer.new InnerClass();

Consider
Considerthe
thefollowing
followingclass
classOuterClass:
OuterClass:

class OuterClass
{
public int x = 0;

class InnerClass
{
public int x = 1;

void print(int x)
{
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("OuterClass.this.x = " + OuterClass.this.x);
}
}
}

that
thatdefines
definesananinner
innerclass
classcalled
calledInnerClass.
InnerClass.Both
BothOuterClass
OuterClassand andInnerClass
InnerClasshas hasa avariable
variable
called
calledx,x,and
andbecause
becausethe thetwotwovariables
variableshashasthe
thesame
samename
nametheytheycan
canshade
shadeforforeach
eachother.
other.
The class InnerClass has a method called print(), and it has a parameter, that
The class InnerClass has a method called print(), and it has a parameter, that is also called is also called
x.x.When
Whenthe themethod
methodrefers
referstotox x(the
(thefirst
firststatement),
statement),ititisisthe
theparameter
parameterthat thatisisreferred
referredto.to.
When
Whenwriting
writingthis.x
this.x(the
(thesecond
secondstatement)
statement)ititisisasasmentioned
mentionedearlier
earlierthetheinstance
instancevariable
variable
that
thatisisreferenced,
referenced,and andthatthatisisthe
theinstance
instancevariable
variableininthe
theclass
classInnerClass.
InnerClass.IfIfyou youwrites
writes
OuterClass.this.x
OuterClass.this.x (the third statement) is the instance variable in the class OuterClass thatitit
(the third statement) is the instance variable in the class OuterClass that
isisrefered.
refered.Performing
Performingthe thefollowing
followingmethod:
method:

private static void test()


{
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.print(23);
}

Download free eBooks at bookboon.com


39
39
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES
CLASSES Inner
Inner classes
Classes
AND COLLECTION CLASSES Inner Classes

you
you get
get the
the result:
result:
you get the result:

x = 23
x = 23
this.x = 1
this.x = 1
OuterClass.this.x = 0
OuterClass.this.x = 0

The
The same
same convention
convention for for solution
solution of
of problems
problems with
with the
the same
same names
names are
are used
used ifif there
there instead
instead
The same convention for solution of problems with the same names are used if there instead
of
of a variable isis aa method.
of aa variable
variable is a method.
method.

4.1
4.1 ITERATORS
ITERATORS
4.1 ITERATORS
IfIf you have an ArrayList:
If you
you have
have an
an ArrayList:
ArrayList:

ArrayList<Integer> list = new ArrayList();


ArrayList<Integer> list = new ArrayList();

you can
you can iterate over
over the elements
elements in the
the list as
as follows:
you can iterate
iterate over the
the elements in
in the list
list as follows:
follows:

for (Integer t : list) System.out.println(t);


for (Integer t : list) System.out.println(t);

Download free eBooks at bookboon.com


Click on the ad to read more
40
40
40
40
JAVA
JAVA 4: JAVA’S TYPE SYSTEM
JAVA4:
4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
AND COLLECTION CLASSES Inner classes
AND COLLECTIONCLASSES
COLLECTION CLASSES Inner
InnerClasses
Classes

IIIhave
havepreviously
have previouslymentioned
previously mentionedthe
mentioned theiterator
the iteratorpattern,
iterator pattern,and
pattern, andthe
and theabove
the abovestatement
above statementisisislegal
statement legalbecause
legal because
because
the
the class
the class ArrayList
class ArrayList implements
ArrayList implements this
implements this pattern,
this pattern, and
pattern, and thus
and thus the
thus the class
the class implements
class implements
implements the the interface
the interface
interface
Iterable<Integer>,
Iterable<Integer>, which
Iterable<Integer>,which defines
whichdefines a principle
definesaaprinciple
principleofof how
ofhow to
howto traverse
totraverse a collection.
traverseaacollection. In
collection.In fact,
Infact, the
theabove
fact,the above
above
statement
statement is
is translated
translated to
to something
something like
like the
the following:
statement is translated to something like the following:following:

for
for (Iterator<Integer>
(Iterator<Integer> itr
itr == list.iterator();
list.iterator(); itr.hasNext();
itr.hasNext(); ))
System.out.println(itr.next());
System.out.println(itr.next());

which
whichisisisan
which anordinary
an ordinaryfor
ordinary forstatement.
for statement.IIIwould
statement. wouldlater
would latertreat
later treatthe
treat theiterator
the iteratorpattern
iterator patternin
pattern indetails
in detailsand
details and
and
including
including how
how it
it is
is implemented,
implemented, but
but as
as an
an example
example of
of the
the use
use of
of inner
inner classes
classes
including how it is implemented, but as an example of the use of inner classes I will below II will
will below
below
shows
showsaaasimple
shows simpleclass
simple classthat
class thatrepresents
that representsthe
represents theprimes:
the primes:
primes:

package
package primeprogram;
primeprogram;

import
import java.util.*;
java.util.*;

public
public class
class Primes
Primes implements
implements Iterable<Long>
Iterable<Long>
{{
private
private long
long pp == 2;
2;
private long m;
private long m;

public
public Primes(long
Primes(long m)
m)
{{
this.m
this.m == m;
m;
}}

public
public Iterator<Long>
Iterator<Long> iterator()
iterator()
{{
pp == 2;
2;
return
return new
new PrimeIterator();
PrimeIterator();
}}

private
private class
class PrimeIterator
PrimeIterator implements
implements Iterator<Long>
Iterator<Long>
{{
public
public boolean
boolean hasNext()
hasNext()
{{
return
return pp <=
<= m;
m;
}}

Download free eBooks at bookboon.com


41
4141
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4:
4: JAVA’S
JAVA’S TYPE
JAVACOLLECTION
AND TYPE SYSTEM
SYSTEM
CLASSES Inner classes
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Inner
Inner Classes
Classes

public
public Long
Long next()
next()
{{
long
long tt == p;
p;
if
if (p
(p ==
== 2)
2) pp == 3;
3; else
else for
for (p
(p +=
+= 2;
2; !isPrime(p);
!isPrime(p); pp +=
+= 2);
2);
return t;
return t;
}}
}}

public
public static
static boolean
boolean isPrime(long
isPrime(long n) n)
{{
if
if (n
(n ==
== 22 ||
|| nn ==
== 33 ||
|| nn ==
== 55 ||
|| nn ==
== 7)
7) return
return true;
true;
if
if (n
(n << 11
11 |||| nn %% 22 ==
== 0)
0) return
return false;
false;
for
for (long
(long tt == 3,
3, mm == (int)Math.sqrt(n)
(int)Math.sqrt(n) ++ 1;1; tt <=
<= m;
m; tt +=
+= 2)
2) if
if (n
(n %% tt ==
== 0)
0)
return
return false;
false;
return
return true;
true;
}}
}}

When
When you
you create
create an
an instance
instance of of the
the class,
class, you
you specify
specify aa positive
positive integer,
integer, and
and the
the object
object
represent
represent all
all primes
primes less
less than
than oror equal
equal to
to this
this number.
number. The
The class
class makes
makes itit possible
possible toto iterate
iterate
the
the prime
prime numbers
numbers thatthat itit represents.
represents. That
That isis you
you can
can write
write something
something like
like the
the following:
following:

Primes
Primes primes
primes == new
new Primes(100);
Primes(100);
for
for (long p : primes) System.out.print(p
(long p : primes) System.out.print(p ++ "" ");
");
System.out.println();
System.out.println();

The
The class
class implements
implements the the interface
interface Iterable<Long>,
Iterable<Long>, which which means
means that
that the
the class
class must
must havehave
aa method called iterator(), which returns an object of the type Iterator<Long>.
method called iterator(), which returns an object of the type Iterator<Long>. An iterator An iterator
isis an
an object
object that
that cancan refer
refer to
to aa particular
particular item
item in
in aa collection
collection (and
(and here
here inin Primes),
Primes), and and
has
has twotwo methods
methods where where hasNext()
hasNext() tests
tests whether
whether you
you havehave reached
reached the
the end
end while
while the
the next()
next()
returns the item that the iterator indicate and at the same time moves
returns the item that the iterator indicate and at the same time moves the iterator forward. the iterator forward.
Iterator<Long>
Iterator<Long> isis an an interface,
interface, and
and you
you has
has to
to write
write aa class
class that
that implements
implements this this interface.
interface.
This
This class
class will
will be
be used
used to
to instantiate
instantiate an an object
object that
that isis an
an internal
internal property
property ofof the
the class
class Primes
Primes
and
and the the class
class isis written
written asas aa inner
inner class
class called
called PrimeIterator.
PrimeIterator. NoteNote that
that the
the class
class isis private
private
so it is only known inside the class
so it is only known inside the class Primes. Primes.

The
The class
class Primes
Primes have
have two
two instance
instance variables,
variables, the
the first
first pp isis the
the prime,
prime, as as currently
currently isis reached,
reached,
while
while the
the other
other mm isis the
the upper
upper limit
limit of of the
the primes,
primes, the the class
class should
should represent.
represent. WhenWhen
PrimeIterator
PrimeIterator is an inner class, it can refer to these variables, and the implementation of
is an inner class, it can refer to these variables, and the implementation of
the class is quite trivial. The class Primes implements the method
the class is quite trivial. The class Primes implements the method iterator() – defined by iterator() – defined by
the
the interface
interface Iterable<Long>
Iterable<Long> –– and and itit sets
sets the
the start
start of
of the
the primes
primes toto 22 and
and returns
returns an an object
object
of
of the
the type
type PrimeIterator.
PrimeIterator.

Download free eBooks at bookboon.com


42
42
42
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Inner classes
AND COLLECTION CLASSES Inner Classes

The
Themost
mostimportant
importantclassclass isis the
the inner
inner PrimeIterator and as
PrimeIterator and as aa typical
typical application
applicationofofananinner
inner
class,
class,but
butititisisalso
alsoan
anexample
exampleof of how
how to
to implement the iterator
implement the iteratorpattern
patternwith
withaacustom
customiterator.
iterator.

AsAscan
canbebeseen
seenfrom
fromthe the above
above example,
example, an
an inner class can
inner class can be
be private,
private,and
andcan
canalso
alsobebeboth
both
public
publicand
andprotected,
protected, and
and the
the meaning
meaning is
is the
the same as that
same as that for
for other
other members
membersofofaaclass.
class.

ItItisisalso
alsopossible
possibleto
to define
define aa class
class in
in aa method:
method:

private static void test()


{
int[] arr = { 2, 3, 5, 7, 11, 13, 17, 19 };

class Counter
{
private int n = 0;

public int value()


{
int t = n;
n = (n + 1) % arr.length;
return t;
}

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

43 at bookboon.com
Download free eBooks
Click on the ad to read more
43
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Inner classes
AND COLLECTION CLASSES Inner Classes
AND COLLECTION CLASSES Inner Classes

}
}

Counter c = new Counter();


Counter c = new Counter();
for (int i = 0; i < 10; ++i) System.out.print(arr[c.value()] + " ");
for (int i = 0; i < 10; ++i) System.out.print(arr[c.value()] + " ");
System.out.println();
System.out.println();
}
}

Such
Such a class isis called a local class and Counter above isis an example. In this case there isis no
Such aa class
class is called
called aa local
local class
class and
and Counter
Counter above
above is an
an example.
example. In In this
this case
case there
there is no
no
good
good reason
reason for
for the
the local
local class,
class, but
but you
you should
should note
note that
that the
the local
local class
class can
can refer
refer to
to local
local
good reason for the local class, but you should note that the local class can refer to local
variables
variables in the method by which itit isis aa part. You will also notice that the class must be
variables inin the
the method
method by by which
which it is a part. part. You
You will
will also
also notice
notice that
that the
the class
class must
must be be
defined
defined before
before itit can
can be
be instantiated.
instantiated.
defined before it can be instantiated.
Consider
Consider then the following class that defines an iterator which iterates over the factorials:
Consider then
then the
the following
following class
class that
that defines
defines an
an iterator
iterator which
which iterates
iterates over
over the
the factorials:
factorials:

package factorials;
package factorials;

import java.util.*;
import java.util.*;

public class Factorial implements Iterable<Long>


public class Factorial implements Iterable<Long>
{
{
public Iterator<Long> iterator()
public Iterator<Long> iterator()
{
{
return new Iterator<Long>()
return new Iterator<Long>()
{
{
private long t = 1;
private long t = 1;
private int i = 0;
private int i = 0;

public boolean hasNext()


public boolean hasNext()
{
{
return i < 20;
return i < 20;
}
}

public Long next()


public Long next()
{
{
return t *= ++i;
return t *= ++i;
}
}
};
};
}
}
}
}

Download free eBooks at bookboon.com


44
44
44
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4:
JAVA 4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND COLLECTION CLASSES Inner classes
AND
AND COLLECTION
JAVA CLASSES
4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Inner
Inner Classes
Classes
AND COLLECTION CLASSES Inner Classes

The
The class
class isis
is called
called Factorial
Factorial and
and implements
implements the the interface
interface Iterable<Long>.
Iterable<Long>. ItIt It must,
must, therefore,
therefore,
The class called Factorial and implements the interface Iterable<Long>. must, therefore,
The
in
in theclass
sameis called
manner Factorial
as the and
classimplements
Primes the
implement interface
the Iterable<Long>.
method iterator(), It
andmust,
in therefore,
this case,
in the
the same
same manner
manner as as the
the class
class Primes
Primes implement
implement the the method
method iterator(),
iterator(), andand inin this
this case,
case,
in
the
the the
classsame
has manner
no other asmembers.
the class Primes
The implement
method the method
iterator() must iterator(),
return an and in
object of this
the case,
type
the class has no other members. The method iterator() must return an object of the type
class has no other members. The method iterator() must return an object of the type
the class has noand
Iterator<Long>
Iterator<Long> other
and members.
hence
hence II has
has toThe
to method
writte
writte iterator()
aa class
class that
that must return
implements
implements thisaninterface.
this object ofThe
interface. the class
The type
class
Iterator<Long> and hence I has to writte a class that implements this interface. The class
Iterator<Long>
does
does not
not have
have to and
to be hence
be knownI outside
known has to writte
outside the a classiterator(),
the method
method that implements
iterator(), and canthis
and can interface.
therefore
therefore be The class
be written
written as
as
does not have to be known outside the method iterator(), and can therefore be written as
does
an
an not
anonymous have to be
class, known
namely outside
a class the
which method
has no iterator(),
name. You and can
should therefore
note the be written
syntax: as
an anonymous
anonymous class, class, namely
namely aa class
class which
which hashas nono name.
name. You
You should
should note
note the the syntax:
syntax:
an anonymous class, namely a class which has no name. You should note the syntax:
return new
return Iterator<Long>()
new Iterator<Long>()
return
{
{ new Iterator<Long>()
{
}
}
}

and
and an
and an anonymous
an anonymous class
anonymous class must
class must
must be be defined
be defined on
defined on the
on the basis
the basis
basis ofof an
of an interface
an interface or
or aaa class
interface or class that
that itit
class that it
and an
inherits. anonymous
With the class
class must
Factorial be defined
defined on
you the
can basis
write a of an interface
statement like: or a class that it
inherits.
inherits. With
With the
the class
class Factorial
Factorial defined
defined you
you can
can write
write aa statement
statement like:
like:
inherits. With the class Factorial defined you can write a statement like:
for
for (long
(long t
t :
: new
new Factorial())
Factorial()) System.out.println(t);
System.out.println(t);
for (long t : new Factorial()) System.out.println(t);

There are
There are many
many examples
examples of of the
the use
use of
of anonymous
anonymous classes,
classes, for
for example
example the
the class
class Primes,
Primes, that
that
There
There are
are many
many examples
examples of
of the
the use
use of
of anonymous
anonymous classes,
classes, for
for example
example the
the class
class Primes,
Primes, that
that
could be
could be written
be written as
written as follows,
as follows, wherein
follows, wherein the
wherein the iterator
iterator isis
the iterator now
is now implemented
now implemented
implemented as as an
as an anonymous
an anonymous class:
anonymous class:
class:
could
could be written as follows, wherein the iterator is now implemented as an anonymous class:
package primeprogram;
package primeprogram;
package primeprogram;
import
import java.util.*;
java.util.*;
import java.util.*;
public
public class
class Primes
Primes implements
implements Iterable<Long>
Iterable<Long>
public
{
{ class Primes implements Iterable<Long>
{ private
private long
long m;
m;
private long m;
public
public Primes(long
Primes(long m)
m)
public
{
{ Primes(long m)
{ this.m
this.m == m;
m;
}
} this.m = m;
}
public
public Iterator<Long>
Iterator<Long> iterator()
iterator()
public
{
{ Iterator<Long> iterator()
{ return
return new
new Iterator<Long>()
Iterator<Long>()
return
{
{ new Iterator<Long>()
{ long
long p
p =
= 2;
2;
long p = 2;
public boolean
public boolean hasNext()
hasNext()
public
{
{ boolean hasNext()
{ return
return pp <=
<= m;
m;
}
} return p <= m;
}

Download free eBooks at bookboon.com


45
45
45
45
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Inner classes
AND COLLECTION CLASSES Inner Classes

public Long next()


{
long t = p;
if (p == 2) p = 3; else for (p += 2; !isPrime(p); p += 2);
return t;
}
};
}

public static boolean isPrime(long n)


{
if (n == 2 || n == 3 || n == 5 || n == 7) return true;
if (n < 11 || n % 2 == 0) return false;
for (long t = 3, m = (int)Math.sqrt(n) + 1; t <= m; t += 2) if (n % t == 0)
return false;
return true;
}
}

Download free eBooks at bookboon.com


Click on the ad to read more
46
46
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Inner classes

EXERCISE 3
Write a program similar to the program Factorials when the program this time should
implements a class Fibonacci, where you can iterate through the fibonacci numbers

0, 1, 1, 2, 3, 5, 8, 13, 21, …

The class Fibonacci must implement the interface Iterable<Long> and should only have a
single method that returns the iterator, and the main program should only print the fibonacci
numbers. The iterator must as in the class Factorial be implemented as an anonymous class.
Note that the largest fibonacci number that you can represent as a long is the number with
index 89.

EXERCISE 4
Write a program called CounterProgram, that opens the follewing window:

The program must have a very simple class named Counter. The class should have an instance
variable of the type int, that from start is 0. The class must have three methods:

-- up(), that increments the counter by 1


-- down(), that decrements the counter by 1
-- getValue(), that returns the value of the counter

Center in the window is a label, that shows the value of the counter. When the user click
on the button Up, the counter should be increased, and when the user click on Down
the counter should be decreased. The event handler to one of the two buttons must be
written as an inner class, and the event handler to the other button must be written as an
anonymous class.

Download free eBooks at bookboon.com


47
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Inner
Innerclasses
Classes

4.2 EXAMPLE:
4.2 EXAMPLE:ZIPCODES
ZIPCODES
I Iwill
willshow
showananexample
exampleofofaaprogram
programwhere
whereyou youcancansearch
searchthe
theDanish
DanishZIP
ZIPcodes.
codes.The
Theuser
user
canenter
can enteraavalue
valuefor
forthe
theZIP
ZIPcode
codeand
andaavalue
valueforforthe
thecity
cityname,
name,and
andthe
theprogram
programwill
will
thenfind
then findthe
theelements
elementsthat
thatmatches
matchesthese
thesevalues,
values,when
whenthethezipcode
zipcodecode
codemust
muststart
startwith
with
theentered
the enteredvalue,
value,while
whilethe
thecity
cityname
namemust
mustcontain
containthe
theentered
enteredvalue.
value.When
Whencomparing
comparingthethe
citynames,
city names,ititshould
shouldnot
notbe
becase-sensitive.
case-sensitive.I Istart
startwith
withaasimple
simplemodel
modelclass
classfor
foraazip
zipcode:
code:

package postprogram;

public class Post


{
private String code; // the zip code
private String city; // name og the town

public Post(String code, String city)


{
this.code = code;
this.city = city;
}

public String getCode()


{
return code;
}

public String getCity()


{
return city;
}

public String toString()


{
return code + " " + city;
}
}

Nextthere
Next thereisiswritten
writtenaaclass
classPostcodes,
Postcodes,that
thatisisan
anencapsulation
encapsulationofofan
anArrayList<Post>.
ArrayList<Post>.There
There
aretwo
are twochallenges
challengesassociated
associatedwith
withthis
thisclass:
class:

1.1.the
thearraylist
arraylistmust
mustbebeinitialized
initializedwith
withPostPostobjects
objects
2.2.the
the class
class should
should have
have two
two iterators
iterators toto iterates
iterates the
the list
list sorted
sorted respectively
respectively by
by zip
zip
codeororcity
code cityname
name

Download free eBooks at bookboon.com


4848
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Inner
Inner classes
Classes

The
The first
first problem
problem isis solved
solved by
by placing
placing aa table
table directly
directly in
in the
the code.
code. ItIt isis obviously
obviously not
not aa very
very
flexible
flexible solution,
solution, but
but postcodes
postcodes does
does not
not change
change frequently,
frequently, soso in
in this
this case
case the
the solution
solution can
can
be
be accepted.
accepted. InIn the
the program,
program, post
post codes
codes are
are laid
laid out
out as
as an
an array
array in
in aa nested
nested class.
class. The
The class
class
isis also public, so others can refer to it. Below is a part of the
also public, so others can refer to it. Below is a part of the class: class:

public static class Data


{
private final String[][] table = {
{ "1000", "København K" },
{ "1001", "København K" },
{ "1002", "København K" },
….
{ "9982", "Ålbæk" },
{ "9990", "Skagen" }
};

public int length()


{
return table.length;
}

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

Download free eBooks at bookboon.com


Click on the ad to read more
49
49
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Inner
AND COLLECTION
JAVA CLASSES
4: JAVA’S TYPE SYSTEM Inner classes
Classes
AND COLLECTION CLASSES Inner Classes
AND COLLECTION CLASSES Inner Classes

public String getCode(int n)


public String getCode(int n)
public
{ String getCode(int n)
{
{ return table[n][0];
return table[n][0];
}return table[n][0];
}
}
public String getCity(int n)
public String getCity(int n)
public
{ String getCity(int n)
{
{ return table[n][1];
return table[n][1];
} return table[n][1];
}
}}
}
}

The constructor of the class Postcodes uses the class Data to initialize an ArrayList<Post>
The
The
The constructor of the class Postcodes uses the class Data to initialize an ArrayList<Post>
withconstructor
Post objects.of the class Postcodes uses the class Data to initialize an ArrayList<Post>
with
with Post
Post objects.
objects.
The second of the above problems are solved by sorting the ArrayList. To sort an array list
The
The
The second of the
the above problems are solved by
by sorting the ArrayList. To
To sort an array list
and second
for that of
matter above problems
any other list ofare solvedyou
objects, sorting be
should theable
ArrayList.
to compare sort
thean array and
objects list
and
and for that matter
for that matter any
anyanother
other list of objects,
list isofgreater you
objects,than should
you another
should be be able to
able to compare the objects and
to determine whether object object. It compare the objects
can be solved and
in several
to
to determine
determine whether an object is greater than another object. It can be solved in several
ways, and onewhether an specify
way is to object is greater than which
a comparator, another is object.
an objectIt can be class
whose solvedimplements
in several
ways,
ways, and
and one
onetheway
way is to specify
is to specify a comparator, which
a comparator,Itwhich is an object
is aansingle whose
objectmethod class implements
whose class implements
(in this case) interface Comparator<Post>. defines
(in this case) the interface Comparator<Post>. It defines a
(in this case) the interface Comparator<Post>. It defines a single method single method

public int compare(Post p1, Post p2)


public int compare(Post p1, Post p2)
public
{ int compare(Post p1, Post p2)
{
{
}
}
}

which
which must
must return
return -1-1 ifif p1
p1 isis less
less than
than p2, p2, 11 ifif the
the p1
p1 isis greater
greater than
than p2p2 and
and 00 ifif they
they are
are
which
which must
must return
return -1
-1 if
if p1
p1 is
is less
less than
than p2,
p2, 1
1 if
if the
the p1
p1 is
is greater
greater than
than p2
p2 and
and 0
0 if
if they
they are
are
the
the same.
same. The
The class
class isis now
now written,
written, so so itit has
has two
two iterators
iterators that
that starts
starts to
to sort
sort the
the post
post codes
codes
the
the same.
same. The
The class
class is
is now
now written,
written, so
so it
it has
has two
two iterators
iterators that
that starts
starts to
to sort
sort the
the post
post codes
codes
by
by respectively
respectively zipcode
zipcode and and city
city name
name and and the
the sort
sort order
order isis defined
defined byby two
two inner
inner classes:
classes:
by
by respectively
respectively zipcode
zipcode and and city
city name
name andand thethe sort
sort order
order isis defined
defined byby two
two inner
inner classes:
classes:
package postprogram;
package postprogram;
package postprogram;
import java.util.*;
import java.util.*;
import java.util.*;
public class Postcodes implements Iterable<Post>
public class Postcodes implements Iterable<Post>
public
{ class Postcodes implements Iterable<Post>
{
{ private ArrayList<Post> list = new ArrayList();
private ArrayList<Post> list = new ArrayList();
private ArrayList<Post> list = new ArrayList();
public Postcodes()
public Postcodes()
public
{ Postcodes()
{
{ Data data = new Data();
Data data = new Data();
Data data i= =new
for (int 0; Data();
i < data.length(); ++i)
for (int i = 0; i < data.length(); ++i)
for (int i = 0; i < data.length(); ++i)
list.add(new Post(data.getCode(i), data.getCity(i)));
list.add(new Post(data.getCode(i), data.getCity(i)));
} list.add(new Post(data.getCode(i), data.getCity(i)));
}
}

Download free eBooks at bookboon.com


50
50
50
50
JAVA 4: JAVA’S TYPE SYSTEM
JAVA COLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Inner classes
AND COLLECTION CLASSES Inner Classes

public Iterator<Post> iterator()


{
list.sort(new CodeCompare());
return list.iterator();
}

public Iterator<Post> iterator2()


{
list.sort(new CityCompare());
return list.iterator();
}

class CodeCompare implements Comparator<Post>


{
public int compare(Post p1, Post p2)
{
return p1.getCode().compareTo(p2.getCode());
}
}

class CityCompare implements Comparator<Post>


{
public int compare(Post p1, Post p2)
{
return p1.getCity().compareTo(p2.getCity());
}
}

public static class Data


{
….
}
}

Note first that the class implements the iterator pattern in the usual way. Next, note the
two inner classes, each of which defines a comparator. In this case, it is easy to define the
comparison, since in either case you should compare strings, and the class String supports
directly comparison. If you consider the implementation of the method iterator(), so it starts
to sort the ArrayList after zip code, which is done using a method sort() and a comparator
object. The class has a different method, which also returns an iterator. It’s called iterator2()
and works in exactly the same way, just it sorts with a second comparator.

Download free eBooks at bookboon.com


51
51
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Inner
Innerclasses
Classes

The
Theabove
aboveclasses
classescan
canbebeseen
seenasasthe
themodel
modelfor forthe
theprogram,
program,aamodel
modelwhich
whichmakes
makesthethedata
data
available
availablewhich
whichthe
theprogram
programmustmustuse.
use.In
Inthis
thiscase,
case,the
theprogram
programshould
shouldselect
selectsome
someofofthethe
objects
objects from
from the
the model
model based
based on
on aa given
given search
search criteria
criteria for
for respectively
respectively the
the zip
zip code
code and
and
the city name. To this end, I have written a Controller
the city name. To this end, I have written a Controller class: class:

public class Controller


{
private Postcodes model = new Postcodes();

public ArrayList<Post> seek(String code, String city, boolean zipcode)


{
ArrayList<Post> list = new ArrayList();
city = city.toLowerCase();
if (zipcode)
{
for (Post p : model)
if (p.getCode().startsWith(code) &&
p.getCity().toLowerCase().contains(city)) list.add(p);
}
else
{

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com


Click on the ad to read more
52
52
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Inner
AND COLLECTION CLASSES Innerclasses
Classes
AND COLLECTION CLASSES Inner Classes

for (Iterator<Post> itr = model.iterator2(); itr.hasNext();)


for (Iterator<Post> itr = model.iterator2(); itr.hasNext();)
{
{
Post p = itr.next();
Post p = itr.next();
if (p.getCode().startsWith(code) &&
if (p.getCode().startsWith(code) &&
p.getCity().toLowerCase().contains(city)) list.add(p);
p.getCity().toLowerCase().contains(city)) list.add(p);
}
}
}
}
return list;
return list;
}
}
}
}

The class
The class creates
creates the
the model,
model, but
but otherwise
otherwise there
there isis only
only one
one method
method toto searching.
searching. The
The
The class creates the model, but otherwise there is only one method to searching. The
methodhas
method hasthree
threeparameters,
parameters,where
wherethethefirst
firsttwo
twoisisthe
thesearch
searchtext,
text,respectively
respectivelyfor
forthe
thezip
zip
method has three parameters, where the first two is the search text, respectively for the zip
codeand
code andthethecity
cityname.
name.The
Thelast
lastparameter
parameterspecifies
specifieswhether
whetherthe
theresults
resultsmust
mustbebesorted
sortedbyby
code and the city name. The last parameter specifies whether the results must be sorted by
zipcode
zip codeororcity
cityname.
name.IfIfthe
theresult
resultshould
shouldbe besorted
sortedby byzip
zipcode
codethethestandard
standarditerator
iteratorisis
zip code or city name. If the result should be sorted by zip code the standard iterator is
usedby
used byiterating
iteratingthrough
throughthe
themodel
modelwithwiththetheusual
usualsyntax:
syntax:
used by iterating through the model with the usual syntax:

for (Post p : model)


for (Post p : model)

Shouldthe
Should the resultbebe sortedby
by cityname,
name, iterator2()isisused
used andthis
this timeyou
you cannot
not use
Should theresult
result besorted
sorted bycity
city name,iterator2()
iterator2() is usedandand thistime
time youcan
can notuse
use
theexpanded
the expandedfor
forstatement,
statement,but
butmust
mustdirectly
directlyrefer
refertotothe
theiterator:
iterator:
the expanded for statement, but must directly refer to the iterator:

for (Iterator<Postnummer> itr = model.iterator2(); itr.hasNext();)


for (Iterator<Postnummer> itr = model.iterator2(); itr.hasNext();)

Nowthere’s
Now there’s justtotogive
give theprogram
program a userinterface
interface andrun
run theprogram,
program, youget
get the
Now there’sjust
just to givethe
the programaauser
user interfaceand
and runthe
the program,you
you getthe
the
followingwindow,
following window,wherewherethere
therehas
hasbeen
beenaasearch:
search:
following window, where there has been a search:

Download free eBooks at bookboon.com


53
53
53
JAVA 4:
JAVA 4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND COLLECTION
AND COLLECTION CLASSES
CLASSES enumeratIons
Enumerations

55 ENUMERATIONS
ENUMERATIONS
As shown,
As shown, you
you can
can define
define constants
constants as
as variables
variables that
that are
are static
static final.
final. An
An alternative
alternative isis to
to use
use
aa so-called
so-called enumeration,
enumeration, and
and an
an example
example might
might be:be:

package enumerations;
public enum
WeekDays { MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY }

Weekdays
Weekdays isis aa reference
reference type
type that
that defines
defines seven
seven values
values and
and as
as an
an example
example you
you can
can write
write the
the
following
following method:
method:

private static void test01()


{
String[] days =
{ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" };
try
{
System.out.println(weekday(rand.nextInt(7) + 1));
System.out.println(weekday(days[rand.nextInt(7)]));
for (WeekDays day : WeekDays.values()) System.out.println(day);
System.out.println(WeekDays.WEDNESDAY.compareTo(WeekDays.MONDAY));
System.out.println(WeekDays.WEDNESDAY.compareTo(WeekDays.FRIDAY));
System.out.println(WeekDays.WEDNESDAY.compareTo(WeekDays.WEDNESDAY));
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}

private static WeekDays weekday(int n) throws Exception


{
switch (n)
{
case 1: return WeekDays.MONDAY;
case 2: return WeekDays.TUESDAY;
case 3: return WeekDays.WEDNESDAY;
case 4: return WeekDays.THURSDAY;
case 5: return WeekDays.FRIDAY;
case 6: return WeekDays.SATURDAY;
case 7: return WeekDays.SUNDAY;
}
throw new Exception("Illegal day");
}

Download free eBooks at bookboon.com


54
54
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Enumerations
AND COLLECTION CLASSES enumeratIons

private static WeekDays weekday(String s) throws Exception


{
return WeekDays.valueOf(s);
}

The
Theexample
exampleshould
shouldonly
onlyshow
showthe thesyntax.
syntax.The Thefirst
firstweekday()
weekday()method
methodhas hasananint
intasasa a
parameter
parameterand
andconverts
convertsitittotoa avalue
valueofoftype
typeWeekdays.
Weekdays.You Youshould
shouldnote,
note,how
howtotorefer
refertoto
the
theindividual
individualvalues
valueswith
withthethedotdotoperator,
operator,andandyouyoushould
shouldnote
notethat
thatthe
themethood’s
methood’stypetypeisis
Weekdays.
Weekdays.The
Thesecond
secondweekday()
weekday()method,
method,has hasa astring
stringasasa aparameter
parameterand
andreturns
returnsa aWeekdays
Weekdays
value
valuethat
thatmatches
matchesthisthisstring.
string.The Thetwo
twomethods
methodsare areused
usedbybythe
thetest
testmethod.
method.HereHereyou
you
should
shouldspecifically
specificallynote
notethat
thatititisispossible
possibletotoloop
loopoveroverananenumeration.
enumeration.YouYoushould
shouldalso
alsonote
note
that
thatan
anenum
enumisiscomparable
comparableand andthat
thatthe
theorder
orderisisdetermined
determinedby bythe
theorder
orderofofthe
thevalues.
values.

Enumerations
Enumerationscan
canhelp
helptotoimprove
improvethe
thereadability
readabilityofofprograms,
programs,and
andititisisrecommended
recommendedtoto
use
useenumerations
enumerationsififa aprogram
programneeds
needsa afinite
finitenumber
numberofofvalues,
values,which
whichare arevalues
valuesthat
thatdo
do
not
notchange.
change.Good
Goodexamples
examplesareareweek
weekdays,
days,month
monthnames,
names,colors
colorsofofplaying
playingcards,
cards,etc.
etc.

Download free eBooks at bookboon.com


Click on the ad to read more
55
55
JAVA4:4:JAVA’S
JAVA JAVA’STYPE
TYPESYSTEM
SYSTEM
ANDCOLLECTION
AND COLLECTIONCLASSES
CLASSES enumeratIons
Enumerations

InInJava
Javaananenum
enumisisaalittle
littlemore
morethan
thanjust
justaalist
listofofconstant
constantvalues
valuesand
andactually
actuallyan
anenum
enumisis
aaclass.
class.Consider
Considerasasan
anexample
examplethe
thefollowing
followingenum enum(where
(whereI Ihave
havenot
notshown
shownallallvalues):
values):

package enumerations;

public enum Kings


{
GOR (936, 958, "Gorm den Gamle"),
HA1 (958, 987, "Harald Blåtand"),
SV1 (987, 1014, "Svend Tveskæg"),

MA2 (1972, 9999, "Margrethem 2."),
NON (0, 0, "Interregnum");

private final int from;


private final int to;
private final String name;

private Kings(int from, int to, String name)


{
this.from = from;
this.to = to;
this.name = name;
}

public int getFrom()


{
return from;
}

public int getTo()


{
return to;
}

public String getName()


{
return name;
}

public String toString()


{
return "[" + name() + "] " + name;
}

Download free eBooks at bookboon.com


5656
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES
CLASSES Enumerations
enumeratIons
AND COLLECTION CLASSES enumeratIons

public static Kings getKing(int year)


public static Kings getKing(int year)
{
{
for (Kings k : Kings.values()) if (k.from <= year && k.to >= year) return k;
for (Kings k : Kings.values()) if (k.from <= year && k.to >= year) return k;
return Kings.NON;
return Kings.NON;
}
}

public static ArrayList<Kings> getKings(String name)


public static ArrayList<Kings> getKings(String name)
{
{
name = name.toLowerCase();
name = name.toLowerCase();
ArrayList<Kings> list = new ArrayList();
ArrayList<Kings> list = new ArrayList();
for (Kings k : Kings.values()) if (k.name.toLowerCase().contains(name))
for (Kings k : Kings.values()) if (k.name.toLowerCase().contains(name))
list.add(k);
list.add(k);
return list;
return list;
}
}
}
}

The
The example
example should
should show
show that
that itit is
is possible
possible toto assign
assign arguments
arguments or or attributes
attributes toto the
the individual
individual
The example should show that it is possible to assign arguments or attributes to the individual
values.
values. Each
Each value
value is
is this
this time
time aa namename of of three
three characters,
characters, which
which is is aa key
key for
for aa Danish
Danish king.
king.
values. Each value is this time a name of three characters, which is a key for a Danish king.
For
For each
each value
value is
is associated
associated three
three arguments
arguments respectively
respectively start
start and
and endend year
year of
of the
the king’s
king’s
For each value is associated three arguments respectively start and end year of the king’s
reign
reign and
and the
the king’s
king’s name
name (or(or the
the queen’s
queen’s name).
name). TheThe argument
argument is is written
written after
after the
the value,
value,
reign and the king’s name (or the queen’s name). The argument is written after the value,
and
and there
there must
must bebe aa corresponding
corresponding private private constructor
constructor that
that initializes
initializes the
the constants
constants with
with
and there must be a corresponding private constructor that initializes the constants with
the
the current
current arguments.
arguments. In In addition
addition the the type
type may
may have
have methods,
methods, and and in in this
this case
case there
there are
are
the current arguments. In addition the type may have methods, and in this case there are
get
get methods
methods to to the
the three
three arguments,
arguments, aa toString()
toString() method,
method, aa method
method whichwhich cancan return
return the
the
get methods to the three arguments, a toString() method, a method which can return the
reign
reign for
for aa specific
specific year,
year, as
as well
well as as aa search
search method.
method. Below
Below isis shown
shown aa testtest method
method using
using
reign for a specific year, as well as a search method. Below is shown a test method using
the
the type
type Kings
Kings
the type Kings

private static void test02()


private static void test02()
{
{
for (Konge konge : Konge.values()) print(konge);
for (Konge konge : Konge.values()) print(konge);
System.out.println("-------------------------------------------------");
System.out.println("-------------------------------------------------");
print(Konge.getKonge(1200));
print(Konge.getKonge(1200));
System.out.println("-------------------------------------------------");
System.out.println("-------------------------------------------------");
for (Konge konge : Konge.getKonger("Frede")) print(konge);
for (Konge konge : Konge.getKonger("Frede")) print(konge);
}
}

private static void print(Konge konge)


private static void print(Konge konge)
{
{
if (!konge.equals(Konge.NON))
if (!konge.equals(Konge.NON))
System.out.println(
System.out.println(
konge.getNavn() + ", " + konge.getFra() + " – " + konge.getTil());
konge.getNavn() + ", " + konge.getFra() + " – " + konge.getTil());
}
}

There
There is
is not
not much
much toto explain,
explain, but
but you
you should
should note
note that
that the
the type’s
type’s methods
methods are
are used
used as
as
There is
methods not
in much
other to explain,
classes. but you should note that the type’s methods are used as
methods in other classes.
methods in other classes.

Download free eBooks at bookboon.com


57
57
57
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Enumerations

EXERCISE 5
Write a program that you can call MonthProgram. Add an enumeration named Months to
the program when the type must represent the months as an enumeration, and when for
each month must be attached an argument that shows the number of days in the month.

The type must beyond a get method for the number of days have a static method that returns
the number of days in the year when the method has to be implemented with a loop that
determines the number of days by iterating over the values of Mounts.

There must also be a toString(), that returns a string with the name of the month and the
number of days in brackets.

Write a test method – the main() method – which just prints the number of days in the year.

There is a particular problem with initializing February correct. Here you should remember
the class GregorianCalendar.

Download free eBooks at bookboon.com


Click on the ad to read more
58
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Enumerations

PROBLEM 2
In this task, you must write a program that simulates that four players are playing poker. If
you do not know the rules of poker, they are simple and are explained below. The purpose
is to show examples of the use of enumerations, and it is recommended that you follow the
procedure below. The program is intended as a vary simplified poker program.

The program must operate in the following manner. There are four players, one of which is
the user, while the three others are virtual players. When starting a new game, each player
is dealt 5 cards. The user can see his own cards but not the three others. An example of
the program’s window is:

After the players has there 5 cards, each player has the opportunity to exchange cards
(possibly none or all cards), and once they have done it, you can view the cards and the
program tells you who has won. You can then choose a new game, and in the middle the
program shows, how many games you have played and how many the you have won.

Download free eBooks at bookboon.com


59
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Enumerations

The program’s main shortcomings (restrictions) are as listed below:

1. There is nothing in deposits, and it makes it very uninteresting to play, as it is the


whole idea of poker, and the ability to bluff falls thus also away.
2. The rules as the three virtual players use to exchange cards is very simple and static.
3. There are always four players, which should be more dynamic.
4. There is always played with 52 cards.

In addition, the user interface is simple. The task has these limitations to make the program
simple. In fact, it is quite complex two solve the first two of the above constraints in a
good way. I will later returns to the task and look at a new version of the program that do
not to have the same restrictions, but in this place you has to focus on types and especially
enumerations and write the program as described below.

In poker each player is dealt 5 cards, and the player that finally (after players have exchanged
cards) has the highest value, has won the game. The values are with decreasing value
downwards (where an ace is always the highest card):

-- straight flush, where you have five subsequent cards of the same color, that is, for
example eight, nine, ten, jack and queen in the same color
-- four of a kind where you have four cards of the same value, that is, for example
four kings
-- full house, where you have a pair and three of a kind, for example two jacks and
three fours
-- flush, where you have five cards of the same color
-- straight, where you have five subsequent cards, but not necessarily in the same color
-- three of a kind where you have three cards with the same value, for example three
sixes, but the last two cards are different and does not have the value six
-- two pairs that is, for example two threes and two aces, while the last card is not
three or an ace
-- a pair where there are two cards with the same values such as two jacks, while the
last three cards are not a jack, not three of a kind or contains a pair
-- high card, where none of the above values occur

In the case that two players have the same value, the card with the highest value is determining,
and are they the same (as an example two players with a pair), it is the value of the first
card, where the two players’ cards are different which determines the order.

Download free eBooks at bookboon.com


60
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Enumerations
enumeratIons

Use
Usethe
thefollowing
followingprocedure
proceduretotowrite
writethe
theprogram:
program:

1)1)

Create
Createa aproject
projectthat
thatyou
youcan
cancall
callCardProgram.
CardProgram.Create
Createa apackage
packagecardprogram.images
cardprogram.imagesand and
copy
copythe
theimages
imagesofofthe
thecards
cardstotothis
thispackage.
package.The
Thecards
cardscan
canbebefound
foundininthe
thefile
filecards.tar.gz.
cards.tar.gz.

Add
Adda aclass
classcalled
calledMainView
MainViewwhenwhenititshould
shouldbebethe
theprogram’s
program’smain
mainwindow
windowandandwrite
writesoso
much
muchcode
codethat
thatthe
theconstructor
constructoropens
opensa a(so
(sofar
farempty)
empty)window.
window.Creates
Createsan
anobject
objectofofthe
theclass
class
ininmain()
main()and
andrun
runthe
theprogram,
program,the
theresult
resultmust
mustbebethat
thatthe
theprogram
programopens
opensa ablank
blankwindow.
window.

2)2)

Add
Addthe
thefollowing
followingtypes
typestotothe
theproject,
project,representing
representingrespectively
respectivelythe
thecolor
colorand
andthe
thevalue
valueofof
a aplaying
playingcard:
card:

package cardprogram;

public enum Color { DIAMOND, HEART, SPADE, CLUBS }

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57


Download free eBooks at bookboon.com
Click on the ad to read more
6161
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES
CLASSES Enumerations
enumeratIons
AND COLLECTION CLASSES enumeratIons

package cardprogram;
package cardprogram;

public enum Value


public enum Value
{ TWWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
{ TWWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

Note that
Note that the last
last type where
where the values
values are sorted,
sorted, and an
an Ace has
has the highest
highest value, what
what
Note that the
the last type
type where the
the values are
are sorted, and
and an Ace
Ace has the
the highest value,
value, what
is the
is the case in
in poker.
is the case
case in poker.
poker.

3)
3)
3)

Add aa class
Add class representing aa playing
playing card, when
when the class
class should have
have two instance
instance variables
Add a class representing
representing a playing card,
card, when the
the class should
should have two
two instance variables
variables
of the
of the type
type Color
Color and
and Value
Value and
and when
when aa playing
playing cards
cards must
must be
be Comparable:
Comparable:
of the type Color and Value and when a playing cards must be Comparable:

package cardprogram;
package cardprogram;

/**
/**
* Represents a playing card by a color and a value.
* Represents a playing card by a color and a value.
*/
*/
public class Card implements Comparable<Card>
public class Card implements Comparable<Card>
{
{
private Color color;
private Color color;
private Value value;
private Value value;


}
}

The class
The class must
must override
override equals(),
equals(), then
then two
two cards
cards are
are equal
equal ifif they
they have
have the
the same
same color
color and
and
The class must override equals(), then two cards are equal if they have the same color and
same value,
same value, and
and where
where two
two cards
cards should
should be
be sorted
sorted only
only by
by their
their value.
value.
same value, and where two cards should be sorted only by their value.

Next, write
Next, write aa class
class Cards
Cards that
that represents
represents aa deck
deck of
of 52
52 cards,
cards, and
and where
where the
the constructor
constructor
Next, write a class Cards that represents a deck of 52 cards, and where the constructor
creates the
creates the 52
52 Card
Card objects:
objects:
creates the 52 Card objects:
package cardprogram;
package cardprogram;

import java.util.*;
import java.util.*;

public class Cards


public class Cards
{
{

public Cards() { }
public Cards() { }

Download free eBooks at bookboon.com


62
62
62
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Enumerations
AND COLLECTION CLASSES enumeratIons
AND COLLECTION CLASSES enumeratIons

public boolean
public boolean empty()
empty() {{ }}

public Kort
public Kort deal()
deal() throws
throws Exception
Exception {{ }}

public void
public void shuffle()
shuffle() {{ }}
}}

Theclass
The
The classis
class isislittle
littlemore
little morethan
more thanan
than anarray
an arrayof
array of52
of 52cards.
52 cards.The
cards. Theclass
The classmust
class musthave
must havetwo
have twoimportant
two importantmethods:
important methods:
methods:

1. shuffle(),
1.
1. shuffle(), which
shuffle(), which shuffles
which shuffles the
shuffles the cards
the cards in
cards in random
in random order.
random order.
order.
2. deal(),
2.
2. deal(), which
deal(), which take
which take the
take the top
the top card
top card from
card from the
from the deck
the deck and
deck and is
and isis used
used to
used to provide
to provide aaa player
provide player aaa card.
player card.
card.

4)
4)
4)

Add aaa type


Add
Add type that
type that defines
that defines the
defines the size
the size of
size of aaa poker
of poker hand:
poker hand:
hand:

package cardprogram;
package cardprogram;
public enum Rank {{ HEIGHT_CARD,
public enum Rank HEIGHT_CARD, ONE_PIAR,
ONE_PIAR, TWO_PAIR,
TWO_PAIR, THREE_OF_A_KIND,
THREE_OF_A_KIND,
STRAIGHT, FLUSH,
STRAIGHT, FLUSH, FULL_HOUSE,
FULL_HOUSE, FOUR_OF_A_KIND,
FOUR_OF_A_KIND, STRAIGHTFLUSH
STRAIGHTFLUSH }}

where the
where the
where order
the order defines
order defines the
defines the size
the size of
of aaa poker
size of poker hand.
poker hand.
hand.

Add
Add aaa class
Add class that
class that defines
defines aaa poker
that defines poker hand:
poker hand:
hand:

package cardprogram;
package cardprogram;

import java.util.*;
import java.util.*;

public class
public class Hand
Hand implements
implements Comparable<Hand>
Comparable<Hand>
{{
private Card[]
private Card[] arr
arr == new
new Card[5];
Card[5]; //
// the
the cards
cards
private CardValues value; // represents the
private CardValues value; // represents the value value of
of the
the hand
hand

/**
/**
** Creates
Creates aa hand
hand by
by taking
taking 55 cards
cards from
from the
the deck.
deck.
* The 5 cards are arranged in increasing
* The 5 cards are arranged in increasing order of order of the
the cards
cards value.
value.
** Then
Then the
the value
value of
of the
the hand
hand is
is determined
determined and
and stored
stored in
in the
the variable
variable value.
value.
* @param cards The
* @param cards The deck deck
** @throws
@throws Exception
Exception If If the
the deck
deck does
does not
not contains
contains 55 cards
cards
*/
*/
public Hand(Cards cards)
public Hand(Cards cards) throws
throws Exception
Exception {}{}

Download free eBooks at bookboon.com


63
63
63
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Enumerations
AND COLLECTION CLASSES enumeratIons

public Card getCard(int n) {}

/**
* Exchange cards (choose new cards for some of the cards).
* After the cards are exchanged the hand's value is determined again.
* @param cards The deck
* @param selected Array indicating which cards (places) to be exchanged
* @return true, if the deck enough cards and all wanted cards are exchanged
*/
public boolean exchange(Cards cards, boolean[] selected) {}

/**
* @return The rank of the hand
*/
public Rank getRank() {}
/**
* Returns a string consisting of the hand's rank and cards
* @return This hand represented as a string
*/
public String toString() {}

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

Download free eBooks at bookboon.com


Click on the ad to read more
64
64
JAVA 4: JAVA’S TYPE SYSTEM
AND 4:
JAVA COLLECTION CLASSES
JAVA’S TYPE SYSTEM Enumerations
AND COLLECTION CLASSES enumeratIons

/**
* If the current object and the parameter are of different rank the
* comparison is trivial.
* Otherwise, it is the values of the cards, that determines the result.
* @param haand The hand that compares with
* @return -1 (<), 1 (>) or 0 (==)
*/
public int compareTo(Hand hand) {}

// Inner class to the value of a hand.


private class CardValues
{
// the cards that are needed to compare two hands in the case that they have
// the same rank
private Value[] value;
private Rank rank; // hand rank

public CardValues(Rank rank, Value … value)


{
this.value = value;
this.rank = rank;
}

public Value getValue(int n)


{
return value[n];
}

public Rank getRank()


{
return rank;
}
}
}
The class has an inner class called CardValues, which represents the value of a hand. The
classclass
The has has
two an
variables, which
inner class partly
called indicates the
CardValues, hand’s
which rank, and
represents the the values
value of a that
hand.should
The
be used
class to compare
has two two
variables, hands.
which These
partly values the
indicates musthand’s
be used to and
rank, determine the that
the values hand’s value
should
in used
be the case that twotwo
to compare players has These
hands. a handvalues
of themust
sameberank.
used to determine the hand’s value
in the case that two players has a hand of the same rank.

Download free eBooks at bookboon.com


65
65
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Enumerations
enumeratIons

5)5)

Write
Writeaaclass
classPlayer,
Player,which
whichrepresents
representsaaplayer
playerwith
withaaname
nameand
andaahand:
hand:

package cardprogram;

public class Player implements Comparable<Player>


{
private String name;
private Hand hand = null;

public Player(String name) {}

public String getName() {}


/**
* @return The player's rank
* @throws Exception If the player has not yet been dealt cards
*/
public Rank getRank() throws Exception {}

public Hand getHand() throws Exception {}

/**
* The user want to exchange cards
* @param cards Deck of cards
* @param selected Indicates which cards are to be exchange
*/
public void exhange(Cards cards, boolean[] selected) {}

/**
* A player other than the user want to exchange cards.
* The method select which cards to exchange.
* @param cards Deck of cards
*/
public void exchange(Cards cards) {}

/**
* Giving the player a hand of 5 cards
* @param cards The deck of cards
* @throws Exception If the deck not has 5 cards
*/
public void deal(Cards cards) throws Exception {}

Download free eBooks at bookboon.com


6666
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
JAVA CLASSES
4: JAVA’S TYPE SYSTEM enumeratIons
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Enumerations
AND COLLECTION CLASSES enumeratIons
/**
* Comparing the cards for two players in relation to the rules of poker.
/**
* The comparison ensure that players are arranged in descending order of value
* Comparing the cards for two players in relation to the rules of poker.
* of cards
* The comparison ensure that players are arranged in descending order of value
* @param player The player to compares with
* of cards
* @return 1 (hand > player.hand) -1 (hand < player.haand) otherwise 0
* @param player The player to compares with
*/
* @return 1 (hand > player.hand) -1 (hand < player.haand) otherwise 0
public int compareTo(Player player) {}
*/
public int compareTo(Player player) {}
// Two players are equal if they have the same name.
public boolean equals(Object obj) {}
// Two players are equal if they have the same name.
}
public boolean equals(Object obj) {}
}
6)
6)
6)
Write a class Poker representing a number of players who are playing poker:
Write a class Poker representing a number of players who are playing poker:
Write a class Poker representing a number of players who are playing poker:
package cardprogram;

package cardprogram;
/**
* Class which represents a number of players who are playing poker.
/**
*/
* Class which represents a number of players who are playing poker.
*/

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

Download free eBooks at bookboon.com


67 Click on the ad to read more
67
67
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Enumerations
AND COLLECTION CLASSES enumeratIons

public class Poker


{
private Cards cards = new Cards();
private Player[] players;

/**
* Creates a poker game with a deck of cards and a number of players.
* @param players The players participating in the game.
*/
public Poker(Player … players) {}

/**
* Starts a new game by shuffle the deck of cards and all players gets
* there cards.
* @throws Exception If there are not enough cards to all players.
*/
public void deal() throws Exception {}

/**
* @return Number of players
*/
public int size() {}

/**
* The player with index n.
* @param n Index
* @return The player with index n
*/
public Player getPlayer(int n) {}

/**
* Exchange cards for the n-th player.
* @param n Index for the player to exchange cards
* @param selected Specifies which card (places) to be exhanged
*/
public void exchange(int n, boolean[] selected) {}

/**
* Exchange cards for the n-th player.
* @param n Index for the player to exchange cards
*/
public void exchange(int n) {}

Download free eBooks at bookboon.com


68
68
JAVA 4: JAVA’S TYPE SYSTEM
AND
JAVACOLLECTION
JAVA 4:
4: JAVA’S CLASSES
JAVA’S TYPE
TYPE SYSTEM
SYSTEM Enumerations
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES enumeratIons
enumeratIons

/**
/**
** Determines
Determines which
which player
player has
has won
won and
and then
then the
the player
player who
who has
has the
the highest
highest cards.
cards.
** @return
@return The
The player
player who
who has
has won
won
*/
*/
public
public Player
Player won()
won() {}
{}
}}

It’s
It’s aaa simple
It’s simple class,
simple class, and
class, and the
and the most
the most important
most important method
important method is
method isis the
the last,
the last, which
last, which returns
which returns the
returns the player
the player
player
who
who
who has has won.
has won.
won.

7)
7)
7)

Add
Add the
Add the following
the following type
following type to
type to keep
to keep track
keep track of
track of who
of who is
who isis who:
who:
who:

package
package cardprogram;
cardprogram;
/**
/**
** Represents
Represents four
four players
players as
as their
their position
position at
at the
the table.
table.
*/
*/
public enum
public enum Orientation
Orientation {{ NORTH,
NORTH, SOUTH,
SOUTH, WEST,
WEST, EAST
EAST }}

Add
Add aa controller
controller class
class that
that must
must keep
keep track
track of
of how
how many
many games
games are
are played
played and
and how
how many
many
the user
the user has
has won,
won, and
and treat
treat events
events from
from the
the three
three buttons
buttons in
in the
the user
user interface:
interface:

1. exchange
1. exchange cards
cards
2.
2. find
find the
the winner
winner
3. new
3. new game
game

With this
With this class
class in
in place
place all
all that
that remains
remains isis to
to write
write the
the code
code to
to the
the application’s
application’s MainView.
MainView.

Download free eBooks at bookboon.com


69
69
69
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Exception handling

6 EXCEPTION HANDLING
In the preceding examples, both in this and the previous books I have used exception handling.
In principle, it is quite simple, but still are a few more things you should know about.

In practice it is often that a method of one reason or another can not perform the desired
operation, for example because the parameters have illegal values, or otherwise an error
occurs when the method is performed. When the method acknowledges the error, it may
of course cancel the action, but it must also make the calling code aware that there is an
error. This can be achieved by let the method raises an exception, or it can be done with
a return value. The last was formerly a widely used method for handling these kinds of
errors, and the way has both its applications and limitations, so I will start there. I will use
the project Students from the previous book, where I will introduce some changes in order
to better error handling.
360°
thinking .

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discoverfree
Download theeBooks
truth atatbookboon.com
www.deloitte.ca/careers
Click on the ad to read more
70
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4:
4:JAVA’S
JAVA’STYPE SYSTEM
JAVACOLLECTION
AND TYPE SYSTEM
CLASSES exCeptIon handlIng
AND
ANDCOLLECTION
COLLECTIONCLASSES Exception
CLASSES exCeptIonhandling
handlIng

III have
have extended
extended the class
class Student with
with a method that
that deletes aa course,
course, and the
the method isis
have extended thethe class Student
Student with aa method
method that deletes
deletes a course, and
and the method
method is
defined inin the
the interface
interface IStudent
IStudent as
as follows:
follows:
defined
defined in the interface IStudent as follows:
/**
/**
* Deletes a course which a student is enrolled or have completed.
** @param
Deletescourse
a course
The which
coursea to
student is enrolled or have completed.
be deleted
** @return
@param course Thethe
true, if course to was
course be deleted
deleted and false otherwise
*
*/ @return true, if the course was deleted and false otherwise
*/
public boolean remove(ICourse course);
public boolean remove(ICourse course);

A course can obviously only be dropped if the student have the course in question. The
AA course
course cancan obviously
obviously only only be
be dropped
dropped ifif the
the student
student have
have the
the course
course in
in question.
question. TheThe
method can fail, and if so, the calling code has to be notified. It could be solved by changing
method
methodcan canfail,
fail,and
andififso,
so,the
thecalling
callingcode
codehashastotobe
benotified.
notified.ItItcould
couldbebesolved
solvedbybychanging
changing
the method so it raises an exception, but here the method instead returns a value (true
the
the method
method so so itit raises
raises an
an exception,
exception, but
but here
here the
the method
method instead
instead returns
returns aa value
value (true
(true
or false) indicating whether the method is performed correctly or not. The method must
oror false)
false) indicating
indicating whether
whether thethe method
method isis performed
performed correctly
correctly oror not.
not. The
The method
method mustmust
therefore have a return value, which tells the users how it was accomplished. In this case,
therefore
therefore have have aa return
return value,
value, which
which tells
tells the
the users
users how
how itit was
was accomplished.
accomplished. In In this
this case,
case,
it is simple to implement the method as the class ArrayList work the same way:
itit isis simple
simple to
to implement
implement the the method
method asas the
the class
class ArrayList
ArrayList work
work the
the same
same way:
way:
public boolean remove(ICourse course)
{public boolean remove(ICourse course)
{return courses.remove(course);
} return courses.remove(course);
}

AA prerequisite
prerequisite for
for the
the method
method works
works is,is, moreover,
moreover, that
that the
the class
class Course
Course overload
overload equals()
equals()
A
withprerequisite for the method works is, moreover, that the class Course overload equals()
with value
value semantics,
semantics, and
and this
this isis not
not the
the case
case and
and you
you have
have to
to implements
implements equals()
equals() in
in the
the
with
class value semantics, and this is not the case and you have to implements equals() in the
class Course:
Course:
class Course:
public boolean equals(Object obj)
{public boolean equals(Object obj)
{if (obj == null) return false;
if (getClass()
if (obj == null)
== return false;
obj.getClass())
if (getClass() == obj.getClass())
return getId().toUpperCase().equals(((Course)obj).getId().toUpperCase());
returnfalse;
return getId().toUpperCase().equals(((Course)obj).getId().toUpperCase());
} return false;
}

The
The useuse of
of the
the return
return values
values as
as an
an indication
indication ofof whether
whether aa method
method waswas properly
properly performed
performed
The
isis an use of the return values as an indication of whether a method was properly performed
an excellent
excellent solution
solution and
and has
has the
the advantage
advantage thatthat itit isis not
not necessary
necessary to
to encapsulate
encapsulate thethe
is
calledan excellent solution and has the advantage that it is not necessary to encapsulate the
called code
code in in aa try/catch.
try/catch. However,
However, itit also
also has
has its
its limitations
limitations or or drawbacks,
drawbacks, ifif the
the method
method
called code in a Where
returns try/catch. However, the it also has its limitations or drawbacks, if the method
returns aa value.
value. Where appropriate,
appropriate, the return
return value
value maymay be be incorrectly
incorrectly interpreted
interpreted as as aa
returns
result a value. Where appropriate, the return value may be incorrectly interpreted as a
result ofof aa return
return value
value rather
rather than
than an
an error
error code.
code. Another
Another problem
problem isis that
that the
the user
user can
can
result
simply of a return value rather than an error code. Another problem is that the user can
simply ignore
ignore the the return
return value,
value, and
and do
do not
not test
test it.
it.
simply ignore the return value, and do not test it.

Download free eBooks at bookboon.com


71
71
71
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Exception
exCeptIonhandling
handlIng

The
The class
class Course
Course has
has aa method
method that
that returns
returns the
the score
score that
that aa student
student has
has achieved
achieved in
in the
the
subject:
subject:

public int getScore() throws Exception


{
if (score == Integer.MIN_VALUE)
throw new Exception("The student has not completed the course");
return score;
}

IfIf the
the students
students do
do not
not yet
yet have
have aa score
score the
the method
method raises
raises an
an exception.
exception. That
That aa student
student has
has
not received a score is known by the variable of score that has the value Integer.MIN_VALUE
not received a score is known by the variable of score that has the value Integer.MIN_VALUE
(which
(whichisis-2147483648),
-2147483648),and andititisisunlikely
unlikelytotobe
beaalegal
legalscore.
score.The
Themethod
methodcould,
could,therefore,
therefore,
simpler be written as follows:
simpler be written as follows:

public int getScore()


{
return score;
}

where
where thethe value
value -2147483648
-2147483648 then then has
has to
to be
be interpreted
interpreted asas an an error
error code,
code, and
and itit would
would
mean
mean that
that the
the method
method couldcould bebe used
used without
without having
having to to be
be placed
placed inin aa try/catch.
try/catch. OnOn the
the
other
other hand,
hand, youyou would
would asas aa mistake
mistake could
could be be using
using the
the error
error code
code asas aa score,
score, with
with the
the
result
result that
that aa calculation
calculation couldcould be
be wrong.
wrong. Another
Another consequence
consequence would would be be that
that the
the user
user in
in
most cases has to test the value and examine whether it is an error
most cases has to test the value and examine whether it is an error code or a legal score. code or a legal score.
In
In this
this case,
case, II prefer
prefer toto keep
keep the
the method
method asas itit is,
is, and
and let
let itit raise
raise an
an exception
exception ifif there
there has
has
not
not yet
yet been
been assigned
assigned aa score.
score.

IfIf you
you have
have aa method
method that
that returns
returns an
an object
object asas such
such the
the following
following method
method from
from the
the class
class
Student
Student

public ICourse getCourses(String id) throws Exception


{
for (ICourse c : courses) if (c.getId().equals(id)) return c;
throw new Exception("Course not found");
}

Download free eBooks at bookboon.com


72
72
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Exception
exCeptIon handling
handlIng

itit can
can raise
raise an
an exception,
exception, because
because the the students
students do
do not
not necessarily
necessarily have
have aa course
course with
with the
the
current
current id.id. Sometimes,
Sometimes, and and perhaps
perhaps eveneven quite
quite often
often you
you see
see this
this problem
problem solved
solved by
by the
the
method
method in in the
the case
case that
that there
there isis no
no course
course returns
returns null:
null:

public ICourse getCourses(String id)


{
for (ICourse c : courses) if (c.getId().equals(id)) return c;
return null;
}

This solution
This solution isis used
used very
very often,
often, when
when itit isis clear
clear that
that null
null means
means an an error
error or
or indicate
indicate that
that
something was
something was not
not found,
found, but
but here
here too
too there
there isis aa risk
risk that
that the
the return
return value
value could
could be
be used
used
as an
as an object
object when
when itit was
was null,
null, and
and the
the result
result would
would be be aa NullPointerException.
NullPointerException.

The conclusion
The conclusion isis that that the
the use
use of
of return
return values
values as
as error
error messages
messages has
has its
its uses,
uses, but
but in
in most
most
cases itit isis better
cases better to
to let
let the
the method
method raise
raise an
an exception.
exception.

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

Download free eBooks at bookboon.com


Click on the ad to read more
73
73
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Exception
exCeptIonhandling
handlIng

6.1
6.1 CHECKED
CHECKEDEXCEPTIONS
EXCEPTIONS
The
Theprinciple
principleininexception
exceptionhandling
handlingisisthat
thata amethod
methodcan canfail,
fail,and
andififso,
so,ititraises
raisesananexception,
exception,
which
whichmeans
meansthat thatthe
themethod
methodimmediately
immediatelyisisinterrupted
interruptedwith witha amessage
messagetotothe themethod
method
that
thatcalled
calledit.it.Called
Calleda amethod
methodthat thatcan
canraise
raiseananexception,
exception,the thecalling
callingcodecodemustmusthandle
handle
this
thisexception,
exception,whichwhichtypically
typicallyconsists
consistsofofencapsulating
encapsulatingthe themethod
methodcall callinina atry/catch.
try/catch.
Otherwise,
Otherwise,the thecalling
callingcode
codeisissending
sendingananexception
exceptionfurther
furtherup upininthe
thehierarchy
hierarchyofofcalling
calling
methods.
methods.TheTheideaideaisisthat
thatthe
themethod
methodthat thatcan
canraise
raiseananexception
exceptioncan canseeseethat
thatsomething
somethingisis
wrong,
wrong,butbutthethemethod
methodcan cannot
notknow
knowhowhowthe theerror
errorshould
shouldbebehandled.
handled.ItItcan, can,however,
however,
send
sendananexception
exceptiontotothe thecalling
callingcode
codeininthe
thehope
hopethat
thatititknows
knowshow howthe theerror
errorshould
shouldbebe
handled,
handled,andanddoes
doesititnot
notthat,
that,ititcan
canforward
forwardthe themessage
messageup upininmethod
methodhierarchy.
hierarchy.

Above,
Above,I Ihave
haveeverywhere
everywherelet letmethods
methodsraise
raiseananexception
exceptionofofthethetype
typeException,
Exception,and
andalthough
although
ititworks,
works,it’s
it’snot
notthe
theidea.
idea.Javas
Javasown
ownclasses
classesraises
raisesmany
manyexceptions
exceptionsand andthey
theyhave
havetypes
typesthat
that
tell
tellusussomething
somethingaboutaboutwhat
whatisisthe
thereason
reasonfor forthe
theexception.
exception.These
Theseexception
exceptiontypes
typesareareallall
directly
directlyororindirectly
indirectlyderived
derivedfrom
fromthetheclass
classException,
Exception,andandalthough
althoughone oneprobably
probablycancanuseuse
some
someofofthese
thesetypes
typesofofexceptions,
exceptions,ititisistypical
typicalthat
thatyou
youininthethecontext
contextofofananapplication
application
defines
definesitsitsown
ownexception
exceptiontypes.
types.The
Thereason
reasonisispartly
partlythat
thatininthis
thiswaywayyou
youcancanclassify
classifythe
the
various
variousexceptions
exceptionsand andtreat
treatthem
themdifferently
differentlybutbutalso
alsothat
thatyou
youget getthe
thechance
chancetotosend
sendvalues
values
totothe
thecalling
callingcode.
code.

InInthe
theproject
projectconcerning
concerningstudents
studentsI Ihave
haveadded
addedthe
thefollowing
followingclass:
class:

package students;

public class StudentsException extends Exception


{
public StudentsException(String message)
{
super(message);
}
}

ItItisisananexception
exceptiontype
typeforforexceptions
exceptionsfor forthis
thisprogram.
program.YouYoushould
shouldnote
notethat
thatthe
theclass
class
does not add anything new, and its sole purpose is to characterize the exceptions
does not add anything new, and its sole purpose is to characterize the exceptions raised raised
bybymethods
methodsofofthetheprogram’s
program’sclasses.
classes.InInthis
thisway,
way,these
theseexceptions
exceptionsare
aredistinguished
distinguishedfrom
from
exceptions raised by Java’s classes. I also added the following exceptiontype which
exceptions raised by Java’s classes. I also added the following exceptiontype which defines defines
the
theexceptions
exceptionstotothe
theclass
classSubject:
Subject:

Download free eBooks at bookboon.com


7474
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA 4: JAVA’S TYPE
AND SYSTEM
AND COLLECTION
COLLECTION CLASSES
CLASSES Exception
exCeptIon handling
handlIng
AND COLLECTION CLASSES exCeptIon handlIng

package
package students;
students;

class
class SubjectException
SubjectException extends
extends StudentsException
StudentsException
{{
private
private String
String field;
field;

public
public SubjectException(String
SubjectException(String message,
message, String
String field)
field)
{{
super(message);
super(message);
this.field
this.field == field;
field;
}}

public
public String
String getField()
getField()
{{
return
return field;
field;
}}
}}

The
Theclass
classSubject
Subjectraises
raisesan
anexception
exceptionififone
oneofofits
itsfields
fieldsareareassigned
assignedananillegal
illegalvalue.
value.Therefore
Therefore
extends
extends this class StudentsException with a variable that indicates which field that isillegal.
this class StudentsException with a variable that indicates which field that is illegal.
Also note that the class is written in the same file as StudentsException and
Also note that the class is written in the same file as StudentsException and thus has package thus has package
visibility.
visibility.ItItwas
waschosen
chosenbecause
becauseititisisaavery
verysimple
simpleclass,class,and
andthethetype
typeshould
shouldnot notbe
beknown
known
outside
outside of the program’s package. With these types the class Subject must be updatedasas
of the program’s package. With these types the class Subject must be updated
follows,
follows,where
whereI Ihavehaveonly
onlyshown
shownthe themethods
methodsthat thatraises
raisesananexception:
exception:

public
public class
class Subject
Subject implements
implements ISubject,
ISubject, IPoint,
IPoint, Cloneable
Cloneable
{{
private
private String
String id;
id; //
// the
the subject
subject id
id
private
private String name; // the subject's
String name; // the subject's name
name
private
private int ects = 0; // the subtect's ECTS
int ects = 0; // the subtect's ECTS

public
public Subject(String
Subject(String id,
id, String
String name)
name) throws
throws SubjectException
SubjectException
{{
this(id,
this(id, name,
name, 0);
0);
}}

public
public Subject(String
Subject(String id,
id, String
String name,
name, int
int ects)
ects) throws
throws SubjectException
SubjectException
{{
ifif (!ISubject.subjectOk(id,
(!ISubject.subjectOk(id, name))
name)) throw
throw new
new
SubjectException("The
SubjectException("The subject must have both
subject must have both an
an ID
ID and
and aa name",
name", "name");
"name");
if (ects < 0) throw new SubjectException("ECTS must be non-negative",
if (ects < 0) throw new SubjectException("ECTS must be non-negative", "ects");"ects");
this.id
this.id == id;
id;
this.name
this.name = name;
= name;
this.ects
this.ects == ects;
ects;
}}

Download free eBooks at bookboon.com


75
75
75
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Exception handling
AND COLLECTION CLASSES exCeptIon handlIng

public void setName(String name) throws SubjectException


{
if (!ISubject.subjectOk(id, name)) throw new
SubjectException("The subject must have a name", "name");
this.name = name;
}

public void setECTS(int ects) throws SubjectException


{
if (ects < 0) throw new SubjectException("ECTS must be non-negative", "ects");
this.ects = ects;
}
}

Note that
Note that also
also the
the interface
interface ISubject
ISubject and
and IPoint
IPoint must
must be
be updated
updated such
such that
that the
the methods
methods
throws the
throws the correct
correct exception
exception types.
types. Also
Also note
note that
that the
the program
program can
can compile
compile and
and run,
run, although
although
the test
the test methods
methods referes
referes to
to Exception
Exception instead
instead of
of SubjectException,
SubjectException, for
for aa SubjectException
SubjectException is
is
especially an
especially an Exception.
Exception.

AXA Global
Graduate Program
Find out more and apply

Download free eBooks at bookboon.com


Click on the ad to read more
76
76
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Exception
exCeptIon handling
handlIng

For
For the
the sake
sake of
of courses
courses II have
have defined
defined the
the following
following exception
exception types:
types:

class CourseException extends StudentsException


{
public CourseException(String message)
{
super(message);
}
}

class ScoreException extends CourseException


{
private int score;

public ScoreException(String message, int score)


{
super(message);
this.score = score;
}

public int getScore()


{
return score;
}
}

Next, the
Next, the class
class Course
Course should
should be
be updated
updated with
with these
these types,
types, and
and the
the same
same applies
applies to
to the
the
interface ICourse.
interface ICourse.

On this
On this place
place II have
have defined
defined four
four exception
exception classes
classes which
which form
form aa hierarchy:
hierarchy:

Download free eBooks at bookboon.com


77
77
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Exception
exCeptIon handling
handlIng

It is very common that exception types for a program in this way consists of a hierarchy
of classes with Exception as a common base class. On the other hand, it depends on the
job, programmer, etc., how far you go and how many types you define, and above I have
probably gone to far which the benefits of the many types is modest.

I’ve also updated four of the methods in the class Factory:

public abstract class Factory


{
public static ISubject createSubject(String id, String name)
throws SubjectException
{
return new Subject(id, name);
}

public static ISubject createSubject(String id, String name, int ects)


throws SubjectException
{
return new Subject(id, name);
}

public static ICourse createCourse(int year, ISubject subject)


throws CourseException
{
return new Course(year, subject);
}

public static ICourse createCourse(int year, String id, String name)


throws CourseException, SubjectException
{
return new Course(year, createSubject(id, name));
}

The four methods return new exceptions similar to those exceptions the concrete constructors
can raise. You should especially notice the last. When createSubject() can raise an exception
of the type SubjectException, the method can raise two kinds of exceptions and you need to
note how you with throws has to indicate that a method can raise several kinds of exceptions.

Download free eBooks at bookboon.com


78
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Exception handlIng
exCeptIon handling

When a method with throws indicates that it may raise an exception, the compiler demands
that the calling code must be placed in a try/catch. Thereby forcing the programmer to
deal with the exceptions that a method can raise. It may seem cumbersome, but it helps to
provide a robust code. Is there anything that can result in an error, then the programmer
must necessarily consider what to do if the error occurs. It’s the whole fundamental principle
of exception handling. Below is a test method:

private static void test()


{
try
{
ICourse course1 = Factory.createCourse(2015, "MAT7", "Mathematics");
course1.setScore(7);
System.out.println(course1.getId());
System.out.println(course1 + " " + scourse1.getScore());
ICourse course2 = Factory.createCourse(2015, "MAT6", "");
System.out.println(course2.getSubject());
}
catch (SubjectException ex)
{
System.out.println(ex.getField() + ": " + ex.getMessage());
}

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

Download free eBooks at bookboon.com


Click on the ad to read more
79
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
JAVA COLLECTION
4: JAVA’S
AND COLLECTION CLASSES
TYPE SYSTEM
CLASSES exCeptIon
exCeptIon handlIng
Exception handling
handlIng
AND COLLECTION CLASSES exCeptIon handlIng

catch
catch (ScoreException
(ScoreException ex)
ex)
{ catch (ScoreException ex)
{
{System.out.println(ex.getMessage());
System.out.println(ex.getMessage());
} System.out.println(ex.getMessage());
}
}catch (CourseException ex)
catch (CourseException ex)
{ catch (CourseException ex)
{
{System.out.println(ex.getMessage());
System.out.println(ex.getMessage());
} System.out.println(ex.getMessage());
}
}finally
finally
{ finally
{
{System.out.println("End!!");
System.out.println("End!!");
} System.out.println("End!!");
}
} }
}
}

The code in the try block can raise three kinds of exceptions, and there is, therefore, three
The code
catch in the
blocks. It istry
theblock
type ofcana possible
raise three kinds ofthat
exception, exceptions, andwhich
determines there catch
is, therefore, three
is performed
catchitblocks.
and It is
is one of thethemain
typereasons
of a possible
to haveexception, that determines
more exception whichincatch
types because this is
wayperformed
you can
and it is one of the main reasons to have more exception types because in
control the action that should happen. In this case there is no particular reason for it, this way yousince
can
control
the errorthe action each
handler that time
should happen.
consists of In this case
printing anthere
errorismessage.
no particular
Note,reason
however,for the
it, since
first
the error handler each time consists of printing an error message. Note,
catch, where I use, that the exception has a method getField(). You should also notice thathowever, the first
catch,
the wherefor
handler I use, that the exception
ScoreException has abefore
must come method thegetField(). YouCourseException
handler for should also notice that
because
athe handler for ScoreException
ScoreException must comeand
also is a CourseException before
the the handler
runtime for CourseException
system looks for a match because
from
astart
ScoreException
to bottom. also is a CourseException and the runtime system looks for a match from
start to bottom.
Finally, there is a finally block. It does not have to be there, and in this case, it has no
Finally,but
sense, there is a finally
a finally block block. It does
is always not have
performed to be there,
regardless and inthere
of whether this iscase, it has no
an exception
sense,
or not.but a finally
It may, block is be
for example always
usedperformed regardless
to close files, of whether
terminate theretois databases
connections an exception
etc.
or not. It may, for example be used
If the method is executed the result is: to close files, terminate connections to databases etc.
If the method is executed the result is:
2015-MAT7
2015-MAT7
2015-MAT7
Mathematics
Mathematics 7
7
Mathematics
name: 7
name: A
A subject
subject must
must have
have a
a name
name
name:
End!! A subject must have a name
End!!
End!!

Here you should note that the last statement in the try block is not executed because it raises
Here
an you should note that the last statement in the try block isthe
not executed because it raises
an exception
exception and
and thus
thus interrupt
interrupt the
the try
try block.
block. Note
Note also
also that
that the finally
finally block
block is
is performed.
performed.
an exception and thus interrupt the try block. Note also that the finally block is performed.
As mentioned, there in this example is no particular need to distinguish between the three
As mentioned,
types there and
of exceptions, in this
the example is no
code could particular
instead need toasdistinguish
be written follows: between the three
types of exceptions, and the code could instead be written as follows:
private
private static
static void
void test()
test()
private
{ static void test()
{
{try
try
try
{
{
{

Download free eBooks at bookboon.com


80
80
80
JAVA 4:
JAVA 4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA
AND 4: JAVA’S TYPE
AND COLLECTION
COLLECTION SYSTEM
CLASSES
CLASSES Exception handlIng
exCeptIon handling
AND COLLECTION CLASSES exCeptIon handlIng

ICourse course1 = Factory.createCourse(2015, "MAT7", "Mathematics");


ICourse course1 = Factory.createCourse(2015, "MAT7", "Mathematics");
course1.setScore(7);
course1.setScore(7);
System.out.println(course1.getId());
System.out.println(course1.getId());
System.out.println(course1 + " " + scourse1.getScore());
System.out.println(course1 + " " + scourse1.getScore());
ICourse course2 = Factory.createCourse(2015, "MAT6", "");
ICourse course2 = Factory.createCourse(2015, "MAT6", "");
System.out.println(course2.getSubject());
} System.out.println(course2.getSubject());
}
catch (StudentsException ex)
catch (StudentsException ex)
{
{ System.out.println(ex.getMessage());
} System.out.println(ex.getMessage());
}
finally
finally
{
{ System.out.println("End!!");
} System.out.println("End!!");
}}
}

for all three kinds of exceptions’s are also a StudentsException.


for all three kinds of exceptions’s are also a StudentsException.

As discussed above a user-defined exception directly or indirectly inherit Exception, and if a


As discussed above a user-defined exception directly or indirectly inherit Exception, and if a
method that can raise such an exception is performed, you must with throws specify which
method that can raise such an exception is performed, you must with throws specify which
exception the method can raise. Such exceptions are said to be checked.
exception the method can raise. Such exceptions are said to be checked.

6.2 UNCHECKED EXCEPTIONS


6.2 UNCHECKED EXCEPTIONS
There is another possibility. I have extended the class Team with a method that returns the
There is another possibility. I have extended the class Team with a method that returns the
n-th student:
n-th student:
public IStudent getStudentAt(int n) throws Exception
public IStudent getStudentAt(int n) throws Exception
{
{
if (n < 0 || n >= list.size()) throw new Exception("Illegal index for Student");
if (n < 0 || n >= list.size()) throw new Exception("Illegal index for Student");
return list.get(n);
return list.get(n);
}
}

It raises
It raises an
an exception
exception ifif nn is
is an
an illegal
illegal index.
index. In
In aa way,
way, it
it is
is not
not interesting,
interesting, because
because if
if nn is
is
It raises
illegal, thean exception
the method
method will if n is an illegal
will automatically
automatically raiseindex.
raise an In a way,
an exception, it is
exception, which not
which is interesting, because
is aa RuntimeException, if
RuntimeException, and n
and itis
it
illegal,
illegal,
is an the method
an exception, will
exception, which automatically
which need
need not raise
not necessarily an
necessarily be exception,
be handled.
handled. Ifwhich
If you is a
you still RuntimeException,
still even
even need
need to and
to capture
capture the it
the
is
is an exception,
index error which
error (possibly need
(possibly because
because ofnot necessarily
of the
the error be handled.
error message)
message) you If you
you could still
could write even
write the need to
the method capture
method as the
as follows:
follows:
index
index error (possibly because of the error message) you could write the method as follows:
public IStudent getStudentAt(int n)
public IStudent getStudentAt(int n)
{
{
if (n < 0 || n >= list.size())
if (n < 0 || n >= list.size())
throw new RuntimeException("Illegal index for Student");
throw new RuntimeException("Illegal index for Student");
return list.get(n);
return list.get(n);
}
}

Download free eBooks at bookboon.com


81
81
81
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Exception handling

so that it now raises a unchecked exception. Note that this means that the method no longer
has a throws, and that in turn means that the method can be used outside of a try/catch.

If you in your own programs uses unchecked exceptions, you should in the same as with
checked exceptions define your own exception types that are classes derived directly or
indirectly from RuntimeException. You must remember, however, that there are rarely good
reasons to use unchecked exceptions. They are intended for exceptions regarding serious
errors where it no longer make sense to continue the program’s execution. Applied unchecked
exceptions in your own programs, you override just the whole idea of exception handling
where you force the calling code to treat any exceptions, but there are situations, and I will
later show examples when I look on abstract data types.

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management [email protected] Follow us on IE MIM Experience

Download free eBooks at bookboon.com


Click on the ad to read more
82
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Exception handling

EXERCISE 6
Open the project PaLib again. The project consists for now of two packages

1. palib.util
2. palib.gui

but there is also a third package, called palib – although NetBeans does not show it. You
must add an exception type called PalibException when it should be in the package palib.
Note that you must enter the name of the package:

You must then add an exception class in the package palib.gui, when the class is called
GuiException and when it must be derived from PalibException.

The class Tools has a method createImageIcon() which loads an image from the application’s
jar file. If the image can not be loaded (may be because the name is wrong) the method
returns null, which is perhaps an unfortunate solution. You must change the method so
that it instead raises a GuiException if an error occurs while loading the image. Remember
that you must also update the comment. Build the project so it is ready for use.

Create a new program, that you can call ImageProgram. Add a package to the project with
the name imageprogram.images. Copy the image stone.jpg (from this books directory) to the
new package. Add a reference to the class library PaLib to the project.

Download free eBooks at bookboon.com


83
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Exception handling

The program must open the following window, where the center contains a label:

When the user click on one button, the program should show the image stone.jpg, an when
the user click on the other button, the result should be a GuiException (for example, because
the name is misspelled).

Download free eBooks at bookboon.com


84
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Generic types

7 GENERIC TYPES
In this chapter I will look at generic types and generic methods. In fact, I already used
generic types many times as such an ArrayList<T>, which indicate the type of the kind of
objects that the list should contain. Similarly, I have used several generic interfaces such as
Comparable<T>. In this section I will show how also user-defined types can be defined generic.

I would start with a class representing a circular buffer. A buffer is a container (with Java
terms a collection), which may contain objects, and to the buffer is associated methods that
manipulate the content. A buffer can be implemented in several ways, but here I will look
at a so-called circular buffer, a buffer with room for a certain number of objects. Such a
buffer can be easily implemented by means of an array:

Download free eBooks at bookboon.com


Click on the ad to read more
85
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Generic types

Basically, there are to a buffer associated two operations called insert() and remove(), where
the first inserts an element into the buffer, while the other removes the oldest element – the
element that has been longest in the buffer. The figure above illustrates an empty buffer,
and the arrow tail is the index where the next element should be inserted. Similarly, the
head is the index of the next element to be removed. Initially, the buffer is empty and the
arrows points to the same place. Below is how the buffer looks after inserted 7 elements –
the method insert() is executed 7 times:

If you then remove two elements – the method remove() is executed 2 times – the picture is:

The elements are in principle remained in the data structure, but there is no access to them.
If you then add 3 elements, you get the result:

Here you should especially note that the tail index wraps around so that the next element
to be inserted is in position 0. The next figure shows the buffer, after 4 additional elements
are removed:

and the latter figure shows the result after insertion of two additional elements:

Download free eBooks at bookboon.com


86
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Generic
generIC types
types

The
The name
name circular
circular buffer
buffer is
is derived
derived from
from the
the indices
indices that
that wraps
wraps around
around when
when they
they reach
reach
the
the end
end of
of the
the array.
array.

It
It is
is simple
simple to to implement
implement suchsuch aa data
data structure,
structure, and and the
the first
first and
and foremost
foremost challenge
challenge is
is to
to
keep
keep track
track of
of when
when thethe buffer
buffer isis full
full and
and empty.
empty. Of Of course
course one
one can
can not
not add
add elements
elements toto aa
full
full buffer,
buffer, just
just as as you
you can
can not
not remove
remove elements
elements fromfrom anan empty
empty buffer.
buffer. The
The problem
problem can
can be
be
solved
solved in in several
several ways,
ways, but
but II will
will use
use aa simple
simple counter
counter that
that counts
counts thethe number
number of of elements.
elements.
This
This requires
requires an an additional
additional variable,
variable, butbut itit is,
is, in
in turn,
turn, easy
easy and
and efficient
efficient to
to implement
implement each
each
method,
method, as as itit is
is easy
easy to
to ask
ask the
the buffer
buffer about
about the the number
number of of elements
elements itit contains.
contains. Following
Following
these
these considerations,
considerations, you you can
can implement
implement aa buffer buffer to
to integers
integers as as follows:
follows:

package generic;

public class IntBuffer


{
private int[] buff; // array to the buffer
private int head = 0; // index to the place in front of the first element
private int tail = 0; // index of the last element of the buffer
private int count = 0; // number of elements in the buffer

public IntBuffer(int n)
{
buff = new int[n];
}

public int getCount()


{
return count;
}

public boolean empty()


{
return count == 0;
}

public boolean full()


{
return count == buff.length;
}

public int peek() throws Exception


{
if (empty()) throw new Exception("The buffer is empty");
return buff[head];
}

Download free eBooks at bookboon.com


87
87
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types

public int remove() throws Exception


{
if (empty()) throw new Exception("The buffer is empty");
int elem = buff[head];
head = next(head);
--count;
return elem;
}

public void insert(int elem) throws Exception


{
if (full()) throw new Exception("The buffer is full");
buff[tail] = elem;
tail = next(tail);
++count;
}

private int next(int n)


{
return (n + 1) % buff.length;
}
}

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

Download free eBooks at bookboon.com


Click on the ad to read more
88
88
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Generic
generIC types
types

There
There isis not
not much
much to to explain,
explain, and
and the
the implementation
implementation isis quite
quite effective.
effective. The
The two
two methods
methods
empty()
empty() andand full()
full() isis trivial
trivial and
and the
the fundamental
fundamental methods
methods insert()
insert() and
and remove()
remove() are
are also
also
effective, since in addition to test for an exception they solely do some simple
effective, since in addition to test for an exception they solely do some simple operations. operations.
You
You should
should also
also note
note thethe method
method peek(),
peek(), which
which returns
returns the
the oldest
oldest element
element inin the
the buffer,
buffer,
but
but without
without removing
removing it. it.

As
As an
an example
example thethe method
method test01()
test01() creates
creates an
an IntBuffer
IntBuffer with
with room
room forfor five
five numbers.
numbers. The
The
program
program will iterate over a loop where it randomly either insert a number or remove aa
will iterate over a loop where it randomly either insert a number or remove
number.
number. Some
Some operations
operations will
will fail
fail because
because the
the buffer
buffer isis either
either full
full or
or empty.
empty.

private static void test01()


{
IntBuffer buffer = new IntBuffer(5);
for (int i = 0; i < 100; ++i)
if (rand.nextBoolean())
try
{
System.out.println("<< " + buffer.remove());
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
else
try
{
int t = rand.nextInt(90) + 10;
buffer.insert(t);
System.out.println(">> " + t);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}

The class
The class IntBuffer,
IntBuffer, however,
however, has
has one
one disadvantage,
disadvantage, as
as itit only
only can
can be
be used
used for
for elements
elements ofof
type int.
type int. To
To use
use aa buffer
buffer to
to other
other types
types of
of elements,
elements, itit isis necessary
necessary to
to add
add aa new
new class.
class. One
One
solution isis to
solution to write
write aa buffer
buffer where
where the
the element
element type
type isis Object:
Object:

Download free eBooks at bookboon.com


89
89
JAVA 4: JAVA’S TYPE SYSTEM
JAVA COLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types

package generic;

public class ObjBuffer


{
private Object[] buff; // array to the buffer
private int head = 0; // index to the place in front of the first element
private int tail = 0; // index of the last element of the buffer
private int count = 0; // number of elements in the buffer

public ObjBuffer(int n)
{
buff = new Object[n];
}

public int getCount()


{
return count;
}

public boolean empty()


{
return count == 0;
}

public boolean full()


{
return count == buff.length;
}

public Object peek() throws Exception


{
if (empty()) throw new Exception("The buffer is empty");
return buff[head];
}

public Object remove() throws Exception


{
if (empty()) throw new Exception("The buffer is empty");
Object elem = buff[head];
head = next(head);
--count;
return elem;
}

Download free eBooks at bookboon.com


90
90
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types

public void insert(Object elem) throws Exception


{
if (full()) throw new Exception("The buffer is full");
buff[tail] = elem;
tail = next(tail);
++count;
}

private int next(int n)


{
return (n + 1) % buff.length;
}
}

You should
You should note
note that
that it
it is
is almost
almost the
the same
same class,
class, and
and itit is
is only
only aa question
question of
of the
the type
type of
of
the elements
the elements everywhere
everywhere is is changed
changed from
from int
int to
to Object.
Object. All
All the
the algorithms
algorithms are
are exactly
exactly the
the
same and
same and have
have the
the same
same effectiveness
effectiveness as
as in
in the
the class
class IntBuffer.
IntBuffer. With
With this
this buffer
buffer you
you can
can
write something
write something like
like the
the following:
following:

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

Download free eBooks at bookboon.com


Click on the ad to read more
91
91
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4:
4: JAVA’S
JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND TYPE SYSTEM
CLASSES Generic types
AND
AND COLLECTION
COLLECTION CLASSES generIC
CLASSES generIC types
types

private
private static
static void
void test03()
test03()
{
{
ObjBuffer
ObjBuffer buffer
buffer =
= new
new ObjBuffer(10);
ObjBuffer(10);
try
try
{
{
buffer.insert("Svend");
buffer.insert("Svend");
buffer.insert(23);
buffer.insert(23);
buffer.insert("Knud");
buffer.insert("Knud");
buffer.insert(3.14);
buffer.insert(3.14);
buffer.insert("Valdemar");
buffer.insert("Valdemar");
buffer.insert(new
buffer.insert(new IntBuffer(5));
IntBuffer(5));
while
while (!buffer.empty()) System.out.println(buffer.remove());
(!buffer.empty()) System.out.println(buffer.remove());
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
System.out.println(ex.getMessage());
System.out.println(ex.getMessage());
}
}
}
}

and
and if the method isis executed the result is
and if
if the
the method
method is executed
executed the
the result
result is
is

Svend
Svend
23
23
Knud
Knud
3.14
3.14
Valdemar
Valdemar
generisk.IntBuffer@6d06d69c
generisk.IntBuffer@6d06d69c

The
The buffer
The buffer
buffer cancan contain
can contain everything
contain everything
everything thatthat
that isis an
is an Object,
an Object,
Object, andand
and inin this
in this case
case itit
this case it isis
is aaa String,
String,
String, anan Integer,
an Integer,
Integer,
aaa String,
String, a Double, a String and an IntBuffer. Note that the compiler
String, a Double, a String and an IntBuffer. Note that the compiler performs auto boxing
a Double, a String and an IntBuffer. Note that the compiler performs
performs auto
auto boxing
boxing
ofof 23
of 23 and
23 and 14.3.
and 14.3.
14.3. It It immediately
It immediately
immediately seemsseems smart,
seems smart,
smart, andand
and inin this
in this case
this case it is also
case itit isis also fine
also fine
fine as as the
as the only
the only thing
only thing
thing
toto do
to do with
do with
with thethe items
the items
items whenwhen removed
when removed
removed from from
from thethe buffer
buffer isis
the buffer that
is that they
that they
they are are printed
printed ––
are printed and
– and any
and any
any
Object
Object has a toString(). In other cases, however, it will be necessary
Object has a toString(). In other cases, however, it will be necessary to test the type of the
has a toString(). In other cases, however, it will be necessary to
to test
test the
the type
type of
of the
the
elements
elements when
when they
they are
are removed
removed from
from the
the buffer
buffer and
and make
make
elements when they are removed from the buffer and make a proper typecast. The biggesta
a proper
proper typecast.
typecast. The
The biggest
biggest
problem,
problem, however,
however, isis
problem, however, that
is that the
that the class
the class ObjBuffer
ObjBuffer isis
class ObjBuffer not
is not type
not type strong,
type strong,
strong, as as you
as you
you can can fill
can fill anything
fill anything
anything
into
into it,
into it, and
and itit
it, and increases
it increases
increases the the risk
the risk of
risk of errors.
of errors. This
errors. This can
This can
can be be solved
be solved
solved by by defining
defining aaa generic
by defining generic type.
generic type.
type.

Looking
Looking
Looking at at the
at the test
the test method
test method test03(),
test03(), itit
method test03(), it isis in
is in fact
in fact that
fact that rarely
that rarely that
rarely that you
that you needs
needs aaa collection,
you needs collection,
collection,
which
which can
which can contain
can contain anything.
contain anything.
anything. It It is far
It isis far more
far more common
more common
common thatthat
that you you need
you need a collection
need aa collection
collection ofof integers,
of integers,
integers,
aaa collection
collection
collection to to strings
to strings or
strings or
or toto objects
to objects
objects of of one
of one type
one type or
type or another.
or another.
another. To To solve
To solve this
solve this problem,
problem, itit
this problem, it isis
is
possible
possible to
to parameterize
parameterize a
a class
class where
where a
a parameter
parameter specifying
specifying the
the
possible to parameterize a class where a parameter specifying the type of the objects that type
type of
of the
the objects
objects that
that
the
the class
the class has
class has to
has to work
to work with.
work with. Such
Such aaa parameterized
with. Such parameterized
parameterized classclass
class isis called
called aaa generic
is called generic class,
generic class, and
class, and
and thethe class
the class
class
buffer
buffer may
buffer may
may bebe written
be written as
written as follows:
as follows:
follows:

Download free eBooks at bookboon.com


92
92
92
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types

package generic;

import java.util.*;

public class Buffer<T> implements IBuffer<T>


{
private T[] buff; // array to the buffer
private int head = 0; // index to the place in front of the first element
private int tail = 0; // index of the last element of the buffer
private int count = 0; // number of elements in the buffer
public Buffer(int n)
{
buff = Utils.createArray(n);
}

public int getCount()


{
return count;
}

public boolean empty()


{
return count == 0;
}

public boolean full()


{
return count == buff.length;
}

public T peek() throws Exception


{
if (empty()) throw new Exception("The buffer is empty");
return buff[head];
}

public T remove() throws Exception


{
if (empty()) throw new Exception("The buffer is empty");
T elem = buff[head];
head = next(head);
--count;
return elem;
}

Download free eBooks at bookboon.com


93
93
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types

public void insert(T elem) throws Exception


{
if (full()) throw new Exception("The buffer is full");
buff[tail] = elem;
tail = next(tail);
++count;
}

private int next(int n)


{
return (n + 1) % buff.length;
}
}

First,
First, observe
observe that
that this
this version
version of
of the
the buffer
buffer isis nearly
nearly identical
identical to
to the
the previous
previous two,
two, and
and
that
that itit isis primarily
primarily aa question
question of
of the
the element
element type
type anywhere
anywhere isis replaced
replaced by
by aa parameter
parameter T.
T.
When the class is declared, you specify that it is
When the class is declared, you specify that it is generic: generic:

public class Buffer<T>

Download free eBooks at bookboon.com


Click on the ad to read more
94
94
JAVA 4:
JAVA 4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
AND COLLECTION CLASSES
CLASSES generIC types
Generic types
AND COLLECTION CLASSES generIC types

and depends on a single parameterized type T. Throughout the class T is used as it was a
and depends on a single parameterized type T. Throughout the class T is used as it was a
concrete
concretetype.
type.The
Thecompiler
compilerofofcourse
coursedo donot
notknow
knowwhatwhatTTis,is,and
andthe
theonly
onlything
thingyou
youcancan
do with a T object is also what you can do with an Object, but for collection
do with a T object is also what you can do with an Object, but for collection classes such classes such
asasBuffer
Bufferisisalso
alsothe
theonly
onlything
thingthat
thatisisneeded.
needed.The
Theonly
onlyproblem
problemisisthe
thecreation
creationofofthethearray,
array,
since you can only create an array whose type is Object – you can not write for example
since you can only create an array whose type is Object – you can not write for example
new
newT[99],
T[99],since
sincethe
thecompiler
compilerdoes
doesnotnotknow
knowwhat
whatTTisisfor
fora atype.
type.AsAsI Ioften
oftenwill
willneed
needtoto
create
createa ageneric
genericarray,
array,I Ihave
havemoved
movedthis thisoperation
operationtotoa amethod
methodinina aclass
classUtils
Utilstotobebeable
able
totouse it in other contexts:
use it in other contexts:

class Utils
class Utils
{
{
public static <T> T[] createArray(int length, T… arr)
public static <T> T[] createArray(int length, T… arr)
{
{
return Arrays.copyOf(arr, length);
return Arrays.copyOf(arr, length);
}
}
}
}

Preliminary simply accept the syntax, but copyOf() is a static method in the class Arrays,
Preliminary simply accept the syntax, but copyOf() is a static method in the class Arrays,
which creates an array of a given length, and copy another array. Note that the class Utils
which creates an array of a given length, and copy another array. Note that the class Utils
is defined in the same file as the class Buffer, but it should be placed somewhere else, what
is defined in the same file as the class Buffer, but it should be placed somewhere else, what
is the topic for the next exercise.
is the topic for the next exercise.

The class Buffer<T> implements an inteface:


The class Buffer<T> implements an inteface:

public class Buffer<T> implements IBuffer<T>


public class Buffer<T> implements IBuffer<T>

and the
and the interface does
does nothing more
more than define
define the class’s
class’s methods. The
The aim is
is alone to
to
and theinterface
interface doesnothing
nothing morethan
than definethethe class’smethods.
methods. Theaim
aim isalone
alone to
show that
show that also an
an interface may
may be generic:
show thatalso
also aninterface
interface maybebegeneric:
generic:

package generic;
package generic;

/**
/**
* Defines a generic buffer for objects of a certain type.
* Defines a generic buffer for objects of a certain type.
*/
*/
public interface IBuffer<T>
public interface IBuffer<T>
{
{
/**
/**
* @return Number of elements in the buffer
* @return Number of elements in the buffer
*/
*/
public int getCount();
public int getCount();

Download free eBooks at bookboon.com


95
95
95
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Generic types
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES generIC types
AND COLLECTION CLASSES generIC types

/**
/**
*
* @return
@return true,
true, if
if the
the buffer is empty
buffer is empty
*/
*/
public
public boolean
boolean empty();
empty();

/**
/**
*
* @return
@return true,
true, if
if the
the buffer is full
buffer is full
*/
*/
public
public boolean
boolean full();
full();

/**
/**
*
* Returns
Returns the
the oldest
oldest (first)
(first) element
element in
in the
the buffer
buffer without
without removing
removing it,
it,
*
* @return The oldest (first) element of
@return The oldest (first) element of the
the buffer
buffer
* @throws Exception If the buffer is
* @throws Exception If the buffer is empty empty
*/
*/
public
public TT peek()
peek() throws
throws Exception;
Exception;

/**
/**
*
* Returns
Returns the
the oldest
oldest (first)
(first) element
element in
in the
the buffer
buffer and
and remove
remove the
the element
element from
from
* the buffer.
* the buffer.
*
* @return
@return The
The oldest
oldest (first)
(first) element
element of
of the
the buffer
buffer
* @throws Exception Iff the buffer is
* @throws Exception Iff the buffer is emptyempty
*/
*/
public
public TT remove()
remove() throws
throws Exception;
Exception;

/**
/**
*
* Adds
Adds an
an element
element to
to the
the buffer.
buffer.
*
* @param elem The element to
@param elem The element to be
be added
added
* @throws Exception If the buffer
* @throws Exception If the buffer is is full
full
*/
*/
public
public void
void insert(T
insert(T elem)
elem) throws
throws Exception;
Exception;
}
}

The
The advantage
advantageofof
Theadvantage generic
ofgeneric types
typesasas
generictypes Buffer<T>
Buffer<T>isis
asBuffer<T> that
isthat the
thatthe compiler
thecompiler
compilercan can test
cantest whether
testwhether the
whetherthe type
thetype
type
isis
is used correctly, and any errors are localized, before a program is used. Therefore, it is not
used
used correctly,
correctly, and
and any
any errors
errors are
are localized,
localized, before
before a a program
program is
is used.
used. Therefore,
Therefore, it
it is
is not
not
advisable
advisable to
to use
use types
types the
the likes
likes ObjBuffer
ObjBuffer as
as they
they increase
increase the
the risk
risk that
that the
the generated
generated
advisable to use types the likes ObjBuffer as they increase the risk that the generated code code
code
containing
containing errors.
containingerrors.
errors.

However,
However,itit
However, should
itshould
shouldbe be noted
benoted that
notedthat the
thatthe type
thetype parameter
parametertoto
typeparameter toaaageneric
generic class
genericclass must
classmust be
mustbe an
bean Object
anObject
Object
and
and can
can not
not be
be a a simple
simple type.
type. As
As an
an example
example you
you can
can not
not
and can not be a simple type. As an example you can not write: write:
write:

Buffer<int>
Buffer<int> buffer
buffer =
= new
new Buffer(10);
Buffer(10);

Download free eBooks at bookboon.com


96
96
96
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Generic types
AND COLLECTION CLASSES generIC types

and
and ifif you
you needs
needs aa buffer
buffer to
to the
the elements
elements of
of aa simple
simple type,
type, itit is
is necessary
necessary to
to use
use wrapper
wrapper
classes:
classes:

Buffer<Integer> buffer = new Buffer(10);

However, itit is
However, is not
not as
as big
big aa problem
problem as
as the
the compiler
compiler in
in many
many contexts
contexts perform
perform the
the required
required
type conversions
type conversions by by auto
auto boxing
boxing and
and auto
auto unboxing.
unboxing.

EXERCISE 77
EXERCISE
In this
In this exercise
exercise you
you shoul
shoul as
as in
in exercise
exercise 66 work
work on
on PaLib.
PaLib.

You must
You must add
add aa new
new exception
exception class
class to
to palib.util
palib.util named
named UtilException.
UtilException.

You must
You must then
then copy
copy the
the two
two types
types IBuffer<T>
IBuffer<T> and
and Buffer<T>
Buffer<T> to
to palib.util
palib.util and
and you
you must
must
modify the
modify the types
types such
such that
that they
they everywhere
everywhere (there
(there are
are three
three methods)
methods) raises
raises aa UtilException
UtilException
instead of
instead of an
an Exception.
Exception. Also
Also remember
remember toto update
update the
the IBuffer<T>
IBuffer<T> and
and remember
remember to to update
update
the comments.
the comments.

Download free eBooks at bookboon.com


Click on the ad to read more
97
97
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Generic
generICtypes
types

Add
Addaaclass
classUtils
Utils(still
(stillininpalib.util).
palib.util).The
Theclass
classshall
shallinitially
initiallyonly
onlyhave
havethe
themethod
methodcreateArray()
createArray()
from
fromthethecorresponding
correspondingclass classininthe
thefile
filewith
withBuffer<T>,
Buffer<T>,and andthen
thenthe
theclass
classshould
shouldbebedeleted
deleted
ininthis
thisfile.
file.

Build
Buildthe
theclass
classlibrary.
library.

Finally,
Finally,write
writeaatest
testprogram
programcalled
calledTestBuffer
TestBufferwhen
whenthisthisprogram
programmust
mustuse
useyour
yourclass
classlibrary
library
and
andperform
performthethesame
sameasasthe
thetest
testmethod
methodtest01()
test01()ininthe
theproject
projectGeneric
Generic(see
(seeabove).
above).

7.1
7.1 MORE
MOREON
ONPARAMETERS
PARAMETERS
The
Thename
nameofofthe
theparameter
parametertype
typeplays
playsno
norole
roleand
andthethetype
typecan
canbe
beanything
anythingandandespecially
especially
also
also another
another generic
generic type.
type. As
As an
an example
example the
the following
following method
method creates
creates an
an ArrayList
ArrayList toto
elements
elementsofofthe
thetype
typeArrayList<Integer>:
ArrayList<Integer>:

private static void test04()


{
ArrayList<ArrayList<Integer>> lists = new ArrayList();
lists.add(new ArrayList());
lists.add(new ArrayList());
lists.get(0).add(2);
lists.get(0).add(3);
lists.get(0).add(5);
lists.get(0).add(6);
lists.get(1).add(23);
lists.get(1).add(29);
for (ArrayList<Integer> list : lists)
{
for (Integer t : list) System.out.print(t + " ");
System.out.println();
}
}

and
andififyou
youexecute
executethe
themethod
methodthe
theresult
resultis:is:

2 3 5 6
23 29

As mentioned, you can specify multiple parameter types, and the class below shows a
As mentioned, you can specify multiple parameter types, and the class below shows a
parameterized class Pair that is parameterized by two parameters:
parameterized class Pair that is parameterized by two parameters:

Download free eBooks at bookboon.com


9898
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types
AND COLLECTION CLASSES generIC types

package generisk;
package generisk;

public class Pair<K, V>


public class Pair<K, V>
{
{
private K key;
private K key;
private V value;
private V value;

public Pair(K key, V value)


public Pair(K key, V value)
{
{
this.key = key;
this.key = key;
this.value = value;
this.value = value;
}
}

public K getKey()
public K getKey()
{
{
return key;
return key;
}
}

public V getValue()
public V getValue()
{
{
return value;
return value;
}
}
}
}

EXERCISE
EXERCISE88
EXERCISE 8
Add
Add
Addthethe class
theclass Pair<K,
classPair<K,
Pair<K,V>V>
V>toto your
toyour class
yourclass library
classlibrary when
whenitit
librarywhen must
mustbebe
itmust added
beadded
addedthethe package
thepackage palib.util.
packagepalib.util.
palib.util.
Create
Create a test program that defines an ArrayList with elements of type
Create a test program that defines an ArrayList with elements of type Pair, wherethe
a test program that defines an ArrayList with elements of type Pair,
Pair, where
where the first
thefirst
first
parameter
parameter isisa a String
String (the
(the name
name of
of a a king),
king), while
while the
the second
second parameter,
parameter,
parameter is a String (the name of a king), while the second parameter, is a Pair<Integer,isisa a Pair<Integer,
Pair<Integer,
Integer>
Integer>
Integer>andand indicates
andindicates the
indicatesthe king’s
theking’s reign.
king’sreign. Place
reign.Place the
Placethe following
thefollowing kings
kingsinin
followingkings the
inthe data
thedata structure:
datastructure:
structure:

---- Gorm
Gorm den
Gormden Gamle,
denGamle, 936,
Gamle,936, 958
936,958
958
---- Harald
Harald Blåtand,
Blåtand, 958,
958, 987
987
Harald Blåtand, 958, 987
---- Svend
Svend Tveskæg,
SvendTveskæg, 987,
Tveskæg,987, 1014
987,1014
1014

and
and print
andprint the
printthe content
contentofof
thecontent the
ofthe data
thedata structure
datastructure on
structureon the
onthe screen
thescreen when
screenwhen the
whenthe result
theresult must
mustbebe
resultmust printed
beprinted
printed
inina a method
method print().
print(). The
The result
result should
should
in a method print(). The result should be be
be

Gorm den Gamle, 936 – 958


Gorm den Gamle, 936 – 958
Harald Blåtand, 958 – 987
Harald Blåtand, 958 – 987
Svend Tveskæg, 987 – 1014
Svend Tveskæg, 987 – 1014

Download free eBooks at bookboon.com


99
99
99
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Generic
generIC types

7.2 RAW CLASSES


Java has a so-called collection API discussed later in this book, which contains generic classes.
An ArrayList is an example, but a generic class may also be used as a so-called raw class in
which you do not indicate a parameter type. Consider the following method:

private static void test05()


{
ArrayList list = new ArrayList();
list.add("Knud");
list.add(3.14);
list.add(new Pair<Integer, String>(1, "Margrete"));
for (Object obj: list) print(obj);
Buffer buffer = new Buffer(10);
try
{
buffer.insert("Knud");
buffer.insert(3.14);
buffer.insert(new Pair<Integer, String>(2, "Margrethe"));
while (!buffer.empty()) print(buffer.remove());
}
catch (Exception ex)
{

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

Download free eBooks at bookboon.com


Click on the ad to read more
100
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Generic types
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES generIC types
AND COLLECTION CLASSES generIC types

System.out.println(ex.getMessage());
System.out.println(ex.getMessage());
}
}
}
}

private
private static
static void
void print(Object
print(Object obj)
obj)
{
{
System.out.println(obj
System.out.println(obj +
+ ":
": "
" ++ obj.getClass());
obj.getClass());
}
}

This
This method
Thismethod creates
methodcreates
createsan an ArrayList,
anArrayList, but
ArrayList,but without
butwithout specifying
specifyingaaaparameter.
withoutspecifying parameter.
parameter.The The compiler
Thecompiler can
compilercan not
cannot
not
check
check the
the type
type of
of the
the objects
objects added
added to
to the
the list,
list, and
and itit processes
processes the
the list,
list, asas was
was the
the
check the type of the objects added to the list, and it processes the list, as was the parameter parameter
parameter
ofof the
ofthe type
thetype Object.
typeObject.
Object.ThisThis means
Thismeans that
meansthat you
thatyou
youcancan
canadd add anything
anythingtoto
addanything the
tothe list.
thelist. The
list.The same
Thesame applies
appliestoto
sameapplies to
custom
custom generic
customgeneric types,
generictypes, and
types,and
andyouyou can
youcan create
createaaaBuffer
cancreate Buffer without
Bufferwithout specifying
specifyingaaaparameter
withoutspecifying parameter type.
type.IfIf
parametertype. If
the
the above
above method
method is
is performed,
performed, you
you get
get the
the
the above method is performed, you get the result: result:
result:

Knud:
Knud: class
class java.lang.String
java.lang.String
3.14:
3.14: class
class java.lang.Double
java.lang.Double
generisk.Pair@6d06d69c:
generisk.Pair@6d06d69c: class
class generisk.Pair
generisk.Pair
Knud:
Knud: class
class java.lang.String
java.lang.String
3.14:
3.14: class
class java.lang.Double
java.lang.Double
generisk.Pair@7852e922:
generisk.Pair@7852e922: class
class generisk.Pair
generisk.Pair

Generally
Generallyitit
Generally itisis not
isnot advisable
advisabletoto
notadvisable use
touse the
usethe raw
theraw versions
versionsofof
rawversions the
ofthe generic
thegeneric classes
genericclasses since
classessince the
sincethe compiler
thecompiler
compiler
can
can not
not type
type check
check and
and leads
leads to
to code
code that
that easily
easily can
can contain
contain
can not type check and leads to code that easily can contain errors. errors.
errors.

7.3
7.3 GENERIC
7.3 GENERIC METHODS
GENERICMETHODS
METHODS
Also,
Also, methods
Also,methods can
methodscan be
canbe defined
bedefined generic.
definedgeneric. Below
Belowisis
generic.Below isaaamethod
method that
methodthat seeks
thatseeks an
seeksan element
elementinin
anelement an
inan array:
anarray:
array:

public
public static
static <T>
<T> int
int linSearch(T[]
linSearch(T[] arr,
arr, T
T elem)
elem)
{
{
for
for (int
(int i
i =
= 0;
0; i
i <
< arr.length;
arr.length; ++i)
++i) if
if (arr[i].equals(elem))
(arr[i].equals(elem)) return
return i;
i;
return -1;
return -1;
}
}

The
The method isisdefined generic, asasititacts on an arbitrary array. The algorithm is simple
The method
method is defined
defined generic,
generic, as it acts
acts on on an an arbitrary
arbitrary array.
array. The
The algorithm
algorithm is is simple
simple
and
and consists only in a run through the array from start to finish. If the element exists, the
and consists
consists only
only inin aa run
run through
through thethe array
array fromfrom start
start to
to finish.
finish. If
If the
the element
element exists,
exists, the
the
method
method returns the element’s index. IfIfititisisnot found, the method returns -1, when it
method returns the element’s index. If it is not found, the method returns -1, when it
returns the element’s index. not found, the method returns -1, when it
can
can not
not bebeaalegally
legally index.
index. You
You should
should note
note that
thatthe
the method
method returns
returns the
theindex
index ofofthe
thefirst
first
can not be a legally index. You should note that the method returns the index of the first
element
element found. You should also note that the method implicitly assumes that the parameter
element found.
found. You
You should
should also
also note
note that
that the
the method
method implicitly
implicitly assumes
assumes that
that the
the parameter
parameter
type
type implements equals() with value semantic. An example of an application of the method
type implements
implements equals()
equals() with
with value
value semantic.
semantic. An An example
example of of anan application
application ofof the
the method
method
could
could be:
be:
could be:

Download free eBooks at bookboon.com


101
101
101
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Generic types
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES generIC types
AND COLLECTION CLASSES generIC types

private static void test06()


private static void test06()
{
{
Integer[] arr = { 2, 3, 5, 7, 11, 13, 17, 19 };
Integer[] arr = { 2, 3, 5, 7, 11, 13, 17, 19 };
System.out.println(Generic.<Integer>linSearch(arr, 11));
System.out.println(Generic.<Integer>linSearch(arr, 11));
System.out.println(linSearch(arr, 12));
System.out.println(linSearch(arr, 12));
}
}

Note
Notethat
thatininthe
thefirst
firstcall
callofofthe
themethod
methodI Iindicates
indicatesthe
theparameter
parametertype,
type,which
whichininprinciple
principle
Note that in the first call of the method I indicates the parameter type, which in principle
isisthe
the correct syntax, but it is not necessary because the compiler from the type of thearray
correct syntax, but it is not necessary because the compiler from the type of the array
is the correct syntax, but it is not necessary because the compiler from the type of the array
arr can see that the parameter type is Integer.
arr can see that the parameter type is Integer.
arr can see that the parameter type is Integer.
I Ihave
havepreviously
previouslyshown
shownthe
themethod
methodcreateArray()
createArray()and
andititisisanother
anotherexample
exampleofofa ageneric
generic
I have previously shown the method createArray() and it is another example of a generic
method.
method.
method.
EXERCISE
EXERCISE99
EXERCISE 9
Add
Addthe
themethod
methodlinSearch()
linSearch()totothe
theclass
classUtils
Utilsininyour
yourclass
classlibrary.
library.
Add the method linSearch() to the class Utils in your class library.
Then
Thenyou
youmust
mustwrite
writea aprogram,
program,that
thatyou
youcan
cancall
callSearchProgram1.
SearchProgram1.The
Theprogram
programmust
musthave
have
Then you must write a program, that you can call SearchProgram1. The program must have
a amethod
method
a method
private static Integer[] createArray(int n)
private static Integer[] createArray(int n)
{
{
}
}

thatcreates
that creates andreturns
returns an arraywith
with n elements,that
that mustbebethe
the evennumbers
numbers
that createsand
and returnsananarray
array withnnelements,
elements, thatmust
must be theeven
even numbers

2,2, 4, 6, 8, 10,…
2,4,4,6,6,8,8,10,

10, …

andafter
and after thearray
array is createdand
and initializedthe
the methodshould
should shufflethe
the elements,such
such
and afterthe
the arrayisiscreated
created andinitialized
initialized themethod
method shouldshuffle
shuffle theelements,
elements, such
theyoccur
they occur in randomorder.
order.
they occurininrandom
random order.

Thereshould
There should alsobebea amethod
method
There shouldalso
also be a method
private static void search(Integer[] arr, int elem)
private static void search(Integer[] arr, int elem)
{
{
}
}

thatsearch
that search an elementininthethe arraywith
with thelibrary
library methodlinSearch().
linSearch(). Themethod
method should
that searchananelement
element in thearray
array withthe
the librarymethod
method linSearch().The
The methodshould
should
printwhere
print wherethetheelement
elementisisfound
foundorornot
notand
andhowhowmany
manynano
nanoseconds
secondsthe
thesearch
searchhas
hastaken.
taken.
print where the element is found or not and how many nano seconds the search has taken.

Download free eBooks at bookboon.com


102
102
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Generic
generIC types
types

In
In the
the main()
main() method
method you
you should
should create
create an
an array
array with
with 10000000
10000000 elements
elements (og
(og the
the type
type
Integer).
Integer). Then
Then you
you should
should run
run aa loop,
loop, where
where you
you must
must enter
enter aa number
number and
and then
then call
call the
the
metod
metod search().
search(). The
The loop
loop must
must repeat
repeat until
until you
you enter
enter 0.
0.

An
An example
example to
to execute
execute the
the program
program could
could be:
be:

? 124
Found at index 3430834 : 23855452
? 1234
Found at index 616 : 63935
? 123
Not found : 58309823
? 0

Download free eBooks at bookboon.com


Click on the ad to read more
103
103
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Generic
generIC types
types

PROBLEM 3
In
In mathematics
mathematics weewee works
works with
with sets
sets and
and you
you can
can think
think of
of aa set
set as
as aa container
container for
for objects
objects
and
and thus
thus aa collection.
collection. A
A set
set is
is characterized
characterized by
by the
the following
following properties:
properties:

--- contains(),
contains(), which
which tests
tests whether
whether anan element
element isis in
in the
the set
set
--- union(),
union(), which
which returns
returns the
the union
union of of the
the current
current set
set and
and another
another set
set
--- intersection(),
intersection(), which
which returns
returns the
the intersection
intersection ofof the
the current
current set
set and
and another
another set
set
--- differense(),
differense(), which
which returns
returns the
the set
set difference
difference between
between the the current
current set
set and
and another
another set
set
--- subset(),
subset(), which
which returns
returns aa subset
subset of
of elements
elements that
that satisfy
satisfy aa certain
certain condition
condition

You
You must
must write
write aa generic
generic class
class that
that represents
represents aa set
set with
with the
the above
above operations.
operations. Start
Start with
with aa
new
new project,
project, you
you can
can call
call SetProgram.
SetProgram. The
The project
project must
must have
have aa class
class with
with the
the above
above methods
methods
and
and the
the following
following methods:
methods:

--- add(),
add(), that
that add
add an
an element
element toto the
the set
set –– ifif the
the element
element already
already exists
exists in
in the
the set
set the
the
operation
operation should
should be
be ignored
ignored
--- remove(),
remove(), that
that remove
remove anan element
element from
from the the set
set –– ifif the
the element
element isis not
not in
in the
the set
set
the
the operation
operation should
should be
be ignored
ignored

Finally,
Finally, the
the class
class must
must implement
implement the
the iterator
iterator pattern:
pattern:

package setprogram;

import java.util.*;
/**
* Class representing a set with the classical set operations.
* The class's goal is the sole to illustrate a generic class, but it has little
* practical use since the methods complexity is bad.
*/
public class Set<T> implements Iterable<T>
{

private ArrayList<T> list = new ArrayList(); // to the elements

/**
* Creates an empty set
*/
public Set() {}

Download free eBooks at bookboon.com


104
104
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
JAVA CLASSES
4: JAVA’S TYPE SYSTEM Generic types
AND COLLECTION CLASSES generIC types

/**
* Creates a set that contains elements.
* @param t The elements that the set must contains
*/
public Set(T … t) {}

/**
* Adds an element to the set. If the element already exists in the set,
* the operation is ignored.
* @param e The element to be added
*/
public void add(T e) {}

/**
* Remove an element from the set. If the element does not exist in the set,
* the operation is ignored.
* @param e The element to be removed
*/
public void remove(T e) {}

/**
* Implements contains.
* @param e The element to be tested
* @return true, if the element is found
*/
public boolean contains(T e) {}

/**
* Implements union
* @param A The set to create an union with this set
* @return The union of the current set and A
*/
public Set<T> union(Set<T> A) {}

/**
* Implements intersection.
* @param A The set to create an intersection with this set
* @return The intersection of the current set and A
*/
public Set<T> intersection(Set<T> A) {}

/**
* Implements set difference
* @param A The set to create a set difference between this set and A
* @return The set difference between this set and A
*/
public Set<T> differens(Set<T> A) {}

Download free eBooks at bookboon.com


105

105
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types

/**
* Implements subset.
* @param ok Selector, indicating the elements to be included in the subset
* @return The elements that meets the selector
*/
public Set<T> subset(ISelect<T> ok) {}

/**
* Implements the iterator pattern.
* @return Iterator, that iterates through all elements in the set
*/
public Iterator<T> iterator() {}
}

Regarding themethod
Regarding the methodsubset(),
subset(),you
you must
must transfer
transfer a method
a method thatthat determines
determines which elements
which
to include
elements to in the subset.
include This can
in the subset. becan
This done by means
be done of anof interface:
by means an interface:

package setprogram;
/**
* Interface, that defines a simple selector for elements in a subset.
*/

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

Download free eBooks at bookboon.com


Click on the ad to read more
106
106
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types

public interface ISelect<T>


{
public boolean select(T e);
}

Whenyou
When youhave
havewritten
writtenthe
theclass,
class,you
youshould
shouldtest
testititfrom
fromthe
themain()
main()method.
method.

Note that
Note that the
the purpose
purpose ofof the
the task
task isis only
only toto show
show an an example
example ofof aa generic
generic class,
class, but
but the
the
class has
class has no
no particular
particular practical
practical interest,
interest, since
since itit isis inefficient.
inefficient. AA set
set asas aa collection
collection type,
type,
inin turn,
turn, has
has interest
interest and
and II will
will inin aa later
later book
book show
show how how toto implements
implements aa set set that
that has
has aa
bettercomplexity.
better complexity.

7.4 BOUND
7.4 BOUNDPARAMETER
PARAMETERTYPES
TYPES
Sometimesyou
Sometimes youcan
canfor
forgeneric
genericmethods
methodsand andclasses
classesbe
beinterested
interestedininputting
puttingrestrictions
restrictionson
on
theparameter
the parametertype,
type,so
soit’s
it’snot
notall
allclasses
classesthat
thatcan
canbebeused.
used.

AboveIIhave
Above haveshown
shownaageneric
genericmethod
methodlinSearch(),
linSearch(),which
whichsearches
searchesforforan
anelement
elementininan anarray.
array.
Themethod
The methodimplements
implementslinear
linearsearch,
search,which
whichisisananalgorithm
algorithmthat
thatsearches
searchesforforan
anelement
element
ininan
anarray
arrayby bycomparing
comparingwith withthe
thearray’s
array’selements
elementsfrom
fromstart
starttotofinish.
finish.IfIfthe
thearray
arrayhas
hasnn
items, itit means
items, means using
using n/2
n/2 comparisons
comparisons inin average.
average. This
This method
method inin turn
turn requires
requires nothing
nothing
about the
about the elements
elements and
and only
only they
they can
can bebe compared
compared withwith equals().
equals(). Therefore,
Therefore, the
the method
method
couldbe
could beapplied
appliedtotoarrays
arraysofofarbitrary
arbitrarytype.
type.

Anothersearch
Another searchmethod
methodisiscalled
calledbinary
binarysearch
searchandandcan canbebeused
usedififyouyouknow
knowininadvance
advancethatthat
thearray
the arrayisissorted,
sorted,forforexample
exampleininascending
ascendingorder.order.The Theprinciple
principleisisthat thatyou
youstart
starttotocompare
compare
withthe
with themiddle
middleelement,
element,and andififititisisthe
theelement
elementtotosought,sought,you youarearefinished.
finished.Otherwise,
Otherwise,itit
examineswhether
examines whetherthe theelement
elementbeing
beingsearched
searchedisisgreater
greaterthanthanor orless
lessthan
thanthethemiddle
middleelement.
element.
IsIs itit bigger
bigger than,
than, you
you know,
know, because
because ofof the the array
array isis sorted
sorted thatthat element,
element, ifif itit exists,
exists, must
must
lieininthe
lie theright
righthalf,
half,ororelse
elseititmust
mustbe beininthe
theleft
leftpart.part.You
Younow nowrepeat
repeatthetheprocedure,
procedure,but but
onlyon
only onthethehalf
halfofofthe
thearray.
array.This
Thismeans
meansthatthatyou youhave havehalved
halvedthe thenumber
numberofofelements
elementstoto
bebe searched.
searched. The The same
same will
will happen
happen next next time,
time, and and inin the
the last
last step
step (if
(if the
the element
element isis notnot
found previously)
found previously) you you get
get aa subarray
subarray whose
whose length
length isis 0.0. IfIf thethe array
array has
has nn elements,
elements, and and
eachiteration
each iterationhalves
halvesthe
thelength,
length,the thenecessary
necessarynumber
numberofofcomparisons
comparisonsisislimitedlimitedby by(as
(asyou
you
just should
just should accept),
accept), but
but for
for large
large values
values ofof n,n, itit isis much
much better
better than
than the
the nn // 2.2. The
The result
result
ofofthis
thislittle
littlequick
quickpresentation
presentationofofbinary binarysearch
searchisisthat thatititisisaasearch
searchmethod
methodthat thatisismuch
much
betterthan
better thanlinear
linearsearch,
search,butbutititisisimportant
importanttotoemphasize
emphasizethat thatititassumes
assumesthatthatthethearray
arraytoto
bebesearched,
searched,isissorted.
sorted.

Download free eBooks at bookboon.com


107
107
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA
AND 4: JAVA’S TYPE
AND COLLECTION
COLLECTION SYSTEM
CLASSES
CLASSES Generic
generIC types
types
AND COLLECTION CLASSES generIC types

It is relatively simple to implement binary search in Java. Below is a generic method, but
It is relatively simple to implement binary search in Java. Below is a generic method, but
it requires that you can compare the elements (whether to take the left half or right half ),
it requires that you can compare the elements (whether to take the left half or right half ),
and the parameter type must therefore implements the interface Comparable:
and the parameter type must therefore implements the interface Comparable:
public static <T extends Comparable<T>> int binSearch(T[] arr, T elem)
public static <T extends Comparable<T>> int binSearch(T[] arr, T elem)
{
{
for (int a = 0, b = arr.length – 1; a <= b; )
for (int a = 0, b = arr.length – 1; a <= b; )
{
{
int m = (a + b) / 2;
int m = (a + b) / 2;
if (arr[m].equals(elem)) return m;
if (arr[m].equals(elem)) return m;
if (arr[m].compareTo(elem) < 0) a = m + 1; else b = m – 1;
if (arr[m].compareTo(elem) < 0) a = m + 1; else b = m – 1;
}
}
return -1;
return -1;
}
}

You
You should
should note
note the
the syntax:
syntax:
You should note the syntax:
T extends Comparable<T>
T extends Comparable<T>

Here, the
Here, the word extends means
word extends means thethe type
type T
T either
either must
must to
to inherit
inherit aa class
class or
or implement
implement an an
interface. In
interface. In this
this case
case it
it is
is the
the interface
interface Comparable<T>,
Comparable<T>, which
which means
means that
that objects
objects of
of the
the
type T
type T can
can be
be compared.
compared. If If you
you try
try to
to apply
apply the
the method
method toto objects
objects that
that do
do not
not directly
directly or
or
indirectly implements
indirectly implements Comparable<T>,
Comparable<T>, you you gets
gets aa compiler
compiler error.
error.

One say
One say that the parameter
that the parameter type
type TT is
is bound
bound toto the
the type
type Comparable<T>.
Comparable<T>. It It can
can of
of course
course
also be
also be used
used inin the
the context
context of
of generic
generic classes.
classes. Below
Below isis aa class
class Point
Point to
to represent
represent aa point
point
of two
of two coordinates.
coordinates. TheThe coordinates
coordinates type
type must
must bebe aa number,
number, and and the
the wrapper
wrapper classes
classes to
to
numbers all
numbers all extends
extends thethe abstract
abstract class
class Number.
Number. Then
Then II can
can write
write aa class
class that
that can
can be
be used
used
by all
by all wrapper
wrapper classes:
classes:

package generic;
package generic;
public class Point<T extends Number>
public class Point<T extends Number>
{
{
private T x;
private T x;
private T y;
private T y;

public Point(T x, T y)
public Point(T x, T y)
{
{
this.x = x;
this.x = x;
this.y = y;
this.y = y;
}
}

Download free eBooks at bookboon.com


108
108
108
JAVA 4: JAVA’S TYPE SYSTEM
JAVA COLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Generic types
AND COLLECTION CLASSES generIC types

public T getX()
{
return x;
}

public T getY()
{
return y;
}

public String toString()


{
return "( " + x + ", " + y + " )";
}

public double length(Point p)


{
return Math.sqrt(sqr(x.doubleValue() – p.x.doubleValue()) +
sqr(y.doubleValue() – p.y.doubleValue()));
}

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com


Click on the ad to read more
109
109
JAVA 4: JAVA’S TYPE SYSTEM
AND
JAVACOLLECTION CLASSES
4: JAVA’S TYPE SYSTEM Generic types
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES generIC types
AND COLLECTION CLASSES generIC types

private double sqr(double x)


private double sqr(double x)
{
{
return x * x;
return x * x;
}
}
}
}

You
You must
You must especially
must especially
especially note note the
note the method
the method length(),
method length(), which
length(), which returns
which returns the
returns the distance
the distance between
distance between
between two two
two
points.
points.
points. InIn order
In order to
order to implement
to implement
implement the the calculation,
the calculation, the
calculation, the method
the method
method usesuses doubleValue()
uses doubleValue()
doubleValue() on on all
on all the
all the
the
coordinates,
coordinates,
coordinates, andand it is possible,
and itit isis possible,
possible, as as
as thethe compiler
the compiler know
compiler know that
know that the
that the
the TT is a Number
T isis aa Number
Number and and thus
and thus
thus
makes
makes this
makes this method
this method available.
method available. The
available. The compiler
The compiler knows
compiler knows on
knows on the
on the other
the other hand
other hand
hand notnot where
not where the
where the type
type isis
the type is
an
an Integer,
an Integer, a Double
Integer, aa Double
Double etc.,etc., But
etc., But it is also
But itit isis also not
also not necessary.
not necessary. Consider
necessary. Consider the
Consider the following
the following test
following test method,
test method,
method,
which
which shows
which shows that
shows that you
that you
you cancan determine
can determine
determine the the distance
the distance between
distance between
between twotwo points,
two points, where
points, where the
where the one
the one has
one has
has
Integer
Integer coordinates,
Integer coordinates,
coordinates, andand
and thethe other
the other
other has has Float
has Float coordinates:
Float coordinates:
coordinates:

private static void test08()


private static void test08()
{
{
Point<Integer> p1 = new Point(5, 7);
Point<Integer> p1 = new Point(5, 7);
Point<Float> p2 = new Point(1.42, 3.14);
Point<Float> p2 = new Point(1.42, 3.14);
System.out.println(p1);
System.out.println(p1);
System.out.println(p2);
System.out.println(p2);
System.out.println(p2.length(p1));
System.out.println(p2.length(p1));
}
}

It
It is possible to bind a parameter type to several types with the following syntax:
It is
is possible
possible to
to bind
bind aa parameter
parameter type
type to
to several
several types
types with
with the
the following
following syntax:
syntax:

class TesClass<T extends Type1 & Type2 & Type3)


class TesClass<T extends Type1 & Type2 & Type3)

Here
Here only
Here only
only oneone of
one of the
of the types
the types can
types can
can bebe
be aaa class,
class, while
class, while the
while the other
the other must
other must be
must be interfaces,
be interfaces, and
interfaces, and the
and the one
the one
one
that
that is a class,
that isis aa class, must
class, must be
must be the
be the first.
the first.
first.

EXERCISE
EXERCISE 10
EXERCISE 10
10
Add
Add the
Add the method
the method binSearch()
method binSearch() to
binSearch() to the
to the class
the class Utils
class Utils in
Utils in your
in your class
your class library.
class library. Then
library. Then you
Then you must
you must write
write aaa
must write
program,
program, that
program, that you
that you can
you can call
can call SearchProgram2.
call SearchProgram2. The
SearchProgram2. The program
The program should
program should
should bebe identical
be identical to
identical to the
to the program
the program
program
SearchProgram1,
SearchProgram1, except
SearchProgram1, except two
except two things
two things
things

1.
1. the
1. the program
the program must
program must use
must use binSearch()
use binSearch() instead
binSearch() instead of
instead of linSearch()
of linSearch()
linSearch()
2.
2. the
2. the method
the method createArray()
method createArray() must
createArray() must not
must not shuffle
not shuffle the
shuffle the elements
the elements
elements

Test
Test the
Test the program
the program and
program and see
see ifif
and see you
if you can
you can observe
observe aaa time
can observe time difference
time difference relative
difference relative to
relative to SearchProgram1.
to SearchProgram1.
SearchProgram1.

Download free eBooks at bookboon.com


110
110
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Generic
generIC types
types

7.5
7.5 GENERIC
GENERIC TYPES
TYPES AND
AND INHERITANCE
INHERITANCE
In
In most
most cases,
cases, the
the use
use of
of generic
generic types
types are
are without
without major
major problems,
problems, but
but the
the compatibility
compatibility
of
of inheritances is not quite what you might expect. If, for example you have aa method
inheritances is not quite what you might expect. If, for example you have method

void show(Number t) { … }

so you
so you can
can immediately
immediately transfer
transfer anan Integer,
Integer, aa Long,
Long, aa Float
Float etc.
etc. as
as an
an actual
actual parameter
parameter to
to
show(), since
show(), since they
they all
all specifically
specifically isis aa Number.
Number. Consider,
Consider, however,
however, the
the following
following methods:
methods:

private static void test09()


{
Point<Integer> p = new Point(1, 2);
show(p);
}

private static void show(Point<Number> p)


{
System.out.println(p);
}

If
If you
you tries
tries to
to compile
compile these
these methods,
methods, you
you get
get an
an error
error that
that says
says that
that pp isis not
not compatible
compatible with
with
Point<Number>. It would perhaps be expected when an Integer is compatible
Point<Number>. It would perhaps be expected when an Integer is compatible with Number with Number
because
because Integer
Integer inherits
inherits Number,
Number, but
but Point<Integer>
Point<Integer> does
does not
not inherit
inherit the the Point<Number>
Point<Number>
and
and therefore
therefore the
the types
types are
are not
not compatible.
compatible.

For
For the
the sake
sake of
of the
the following,
following, itit isis necessary
necessary to
to look
look at
at type
type inteference.
inteference. It
It deals
deals with
with how
how
the
the compiler treats the call of a method and the definitions of objects to determine the
compiler treats the call of a method and the definitions of objects to determine the
type
type of
of the
the arguments
arguments andand thus
thus determine
determine whether
whether thethe call
call isis possible.
possible. In
In this
this context,
context, the
the
compiler attempts to determine the most specific type which can be used
compiler attempts to determine the most specific type which can be used for all arguments. for all arguments.
This
This has
has importance
importance with
with generic
generic methods
methods and
and isis best
best explained
explained with with an
an example:
example:

private static void test10()


{
Number t1 = value(new Integer(23), new Double(3.14));
// Float t2 = value(new Integer(23), new Double(3.14));
}

private static <T> T value(T t1, T t2)


{
return rand.nextBoolean() ? t1 : t2;
}

Download free eBooks at bookboon.com


111
111
JAVA
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION CLASSES Generic types
AND COLLECTION CLASSES
COLLECTION CLASSES generIC
generIC types
types

The
The example
example does
does not
not perform
perform something
something interesting
interesting and and must
must onlyonly show
show that
that itit isis legal
legal
code
code that
that can
can be
be compiled
compiled correctly.
correctly. value()
value() isis aa generic
generic method
method with with one
one type
type parameter.
parameter.
The
The method has two parameters of this type, and returns a random of these objects. The
method has two parameters of this type, and returns a random of these objects. The
first
first statement in test10() is legal, since both Integer and Double inherits Number. They are
statement in test10() is legal, since both Integer and Double inherits Number. They are
therefore
therefore type
type inferente,
inferente, and
and the
the compiler
compiler can can compile
compile the the code
code andand type
type parameter
parameter will will at
at
runtime
runtime be be aa Number.
Number. In In turn,
turn, the
the last
last statement
statement in in test10()
test10() isis not
not permitted,
permitted, since
since FloatFloat
isis not type inferent with Integer or Double. Put a little different type
not type inferent with Integer or Double. Put a little different type inference is a matterinference is a matter
that
that the
the compiler
compiler out out of
of the
the context
context cancan see
see the
the type
type toto be
be used
used for
for aa type
type parameter.
parameter. That’s
That’s
why
why youyou can
can call
call the
the generic
generic method
method linSearch()
linSearch() as as

System.out.println(Tools.linSearch(arr, 12));

instead
instead of
of writing
writing

System.out.println(Generic.<Integer>linSearch(arr, 11));

Download free eBooks at bookboon.com


Click on the ad to read more
112
112
112
JAVA
JAVA
JAVA4:4:
4:JAVA’S
JAVA’STYPE
JAVA’S TYPESYSTEM
TYPE SYSTEM
SYSTEM
AND
AND
ANDCOLLECTION
COLLECTION
COLLECTIONCLASSES
CLASSES
CLASSES Generic
generIC
generICtypes
types
types

ItIt
Itisis
ispossible
possibletoto
possible touse
usewild
use wildcards,
wild cards,which
cards, whichisis
which isa aa? ??and
andindicates
and indicatesanan
indicates anunknown
unknowntype.
unknown type.ItIt
type. Itcan
canbebe
can beused
used
used
toto
towrite
write
writemore
more
moregeneral
general
generalmethods.
methods.
methods.Consider
Consider
Considerthe the
thefollowing
following
followingcode:
code:
code:

private static
private static void
void test11()
test11()
{
{
print1(create(2, 3,
print1(create(2, 3, 3.14,
3.14, 1.42));
1.42));
// print1(create(2, 3, 5, 7));
// print1(create(2, 3, 5, 7));
// print1(create(2.1,
// print1(create(2.1, 3.2,
3.2, 5.3,
5.3, 7.4));
7.4));
}
}

private
private static
static <T>
<T> ArrayList<T>
ArrayList<T> create(T
create(T …
… values)
values)
{
{
ArrayList<T>
ArrayList<T> list
list =
= new
new ArrayList();
ArrayList();
for (T t : values) list.add(t);
for (T t : values) list.add(t);
return
return list;
list;
}
}

private
private static
static void
void print1(ArrayList<Number>
print1(ArrayList<Number> list)
list)
{
{
for
for (Number
(Number n
n :
: list)
list) System.out.print(n
System.out.print(n +
+ "
" ");
");
System.out.println();
System.out.println();
}
}

which
which
whichcan canbebe
can betranslated
translatedand
translated andrun,
and run,and
run, anditit
and itisis
isprobably
probablynot
probably notsoso
not sovery
verystrange.
very strange.When
strange. Whencreate()
When create()isis
create() is
called,
called, there
called,there are
are44
thereare actual
4actual parameters
actualparameters
parametersthat that because
becauseofof
thatbecause ofthethe auto
theauto boxing
autoboxing
boxingare are converted
areconverted
convertedintointo
into
objects
objects of type
objectsofoftype Integer
typeInteger and
Integerand
andthethe type
thetype Double.
typeDouble. Because
Double.Because of
Becauseofofthe the type
thetype inferencen
typeinferencen
inferencenthethe method
themethod
method
create()
create() creates
create()creates an ArrayList
createsananArrayList of objects
ArrayListofofobjects of
objectsofofthe the type
thetype Number
typeNumber
Numberand and thus
andthus an object
thusananobject of the
objectofofthe type
thetype
type
ArrayList<Number>.This
ArrayList<Number>.
ArrayList<Number>. Thisobject
This objectcan
object canbebe
can betransferred
transferredasas
transferred asa aaparameter
parametertoto
parameter tothe
themethod
the methodprint1().
method print1().
print1().
IfIf you
youinin
Ifyou the
inthe method
themethod test11()
methodtest11() removes
test11()removes
removesthe the first
thefirst comment,
firstcomment,
comment,you you gets
getsa aacompiler
yougets compiler error.
compilererror. create()
error.create()
create()
is called
isiscalled again
calledagain with
againwith 4 actual
with44actual parameters,
actualparameters,
parameters,but but
butthisthis time
thistime they
timethey
theyareare boxed
areboxed as objects
boxedasasobjects of the
objectsofofthe type
thetype
type
Integer.
Integer.
Integer.TheThe method
Themethod
methodwill will return
willreturn an object
returnananobject to
objecttotothe the type
thetype ArrayList<Integer>,
typeArrayList<Integer>,
ArrayList<Integer>,and and as explained
andasasexplained
explained
inin the
inthe beginning
beginningofof
thebeginning this
ofthis section,
section,itit
thissection, itisis not
isnot compatible
notcompatible
compatiblewith with
withthethe parameter
parametertoto
theparameter print1().
toprint1().
print1().TheThe
The
problem
problem can
can be
be solved
solved with
with a a
problem can be solved with a wildcard: wildcard:
wildcard:

private static
private static void
void print1(ArrayList<?
print1(ArrayList<? extends
extends Number>
Number> list)
list)
{
{
for (Number
for (Number n
n :
: list)
list) System.out.print(n
System.out.print(n +
+ "
" ");
");
System.out.println();
System.out.println();
}
}

The method
Themethod print1()
print1()isis
methodprint1() now
isnow called
nowcalled with
witha aaparameter
calledwith parameter
parameterofof type
oftype ArrayList<T>
typeArrayList<T> where
whereTT
ArrayList<T>where inherits
Tinherits
inherits
The
(or implements)
(orimplements) Number.
implements)Number.
Number.The The type
Thetype Number
typeNumber is called
Numberisiscalled an upper
calledananupper bound.
upperbound.
bound.
(or

Download free eBooks at bookboon.com


113
113
113
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA
JAVA4:4:
4:JAVA’S
JAVA’S
JAVA’STYPE
TYPE
TYPESYSTEM
SYSTEM
SYSTEM
AND COLLECTION CLASSES generIC types
AND
AND
ANDCOLLECTION
COLLECTION
COLLECTIONCLASSES
CLASSES
CLASSES Generic
generIC
generICtypes
types
types

Thewildcards
The wildcards do not needs
needstoto
tobebe bounded, and you can write
writea aamethod
method like the following:
The wildcardsdo
donot
notneeds bebounded,
bounded,and
andyou
youcan
canwrite methodlike
likethe
thefollowing:
following:

private static void print2(ArrayList<?> list)


private
private static
static void
void print2(ArrayList<?>
print2(ArrayList<?> list)
list)
{
{
{
for (Object obj : list) System.out.print(obj + " ");
for
for (Object
(Object obj
obj :
: list)
list) System.out.print(obj
System.out.print(obj +
+ "
" ");
");
System.out.println();
System.out.println();
System.out.println();
}
}
}

It will accept
willaccept any
acceptany ArrayList<T>
ArrayList<T>asas
anyArrayList<T> asa aaparameter.
parameter. Unbounded
parameter.Unbounded wildcards
Unboundedwildcards has
wildcardshas not
notsoso
hasnot many
somany uses
manyuses
uses
ItItwill
but can
butcan be used
canbebeused if the
usedififthe method
themethod only
methodonly perceive
onlyperceive an element
perceiveananelement as an Object.
elementasasananObject.
Object.
but

A wild card
wildcard may
cardmay also
mayalso have
havea aalower
alsohave lower bound:
lowerbound:
bound:
AAwild

private static void print3(ArrayList<? super Integer> list)


private
private static
static void
void print3(ArrayList<?
print3(ArrayList<? super Integer> list)
super Integer> list)
{
{
{
for (int i = 0; i < list.size(); ++i) System.out.print(list.get(i) + " ");
for
for (int
(int i
i =
= 0;
0; i
i << list.size();
list.size(); ++i)
++i) System.out.print(list.get(i) + "
System.out.print(list.get(i) + " ");
");
System.out.println();
System.out.println();
System.out.println();
}
}
}

The
The syntax isis simple enough and means that the method as a a parameter can use any
The syntax
syntax is simple
simple enough
enough and
and means
means that
that the
the method
method as as a parameter
parameter can
can use
use any
any
ArrayList<T>
ArrayList<T> where
where the
theparameter
parameter type
typeTTisisa asuper
supertype
typeofofInteger.
Integer.This
Thismeans
meansthat
thatInteger
Integer
ArrayList<T> where the parameter type T is a super type of Integer. This means that Integer
must
must inherit ororimplement T. As an example you can write:
must inherit
inherit or implement
implement T.
T. As
As anan example
example you you can
can write:
write:

private static void test13()


private
private static
static void
void test13()
test13()
{
{
{
print3(create(2, 3, 3.14, 1.42));
print3(create(2,
print3(create(2, 3,
3, 3.14,
3.14, 1.42));
1.42));
print3(create(2, 3, 5, 7));
print3(create(2,
print3(create(2, 3,
3, 5,
5, 7));
7));
ArrayList<Double> list = create(2.1, 3.2, 5.3, 7.4);
ArrayList<Double>
ArrayList<Double> list
list =
= create(2.1, 3.2, 5.3,
create(2.1, 3.2, 5.3, 7.4);
7.4);
// print3(list);
//
// print3(list);
print3(list);
}
}
}

The
The first
Thefirst create()
firstcreate() creates
createsasas
create()creates mentioned
mentionedanan
asmentioned ArrayList<Number>,
anArrayList<Number>, which
ArrayList<Number>,which
whichmaymay
maybebe used
usedasas
beused asa aaparameter
parameter
parameter
to print3(),
totoprint3(), because
print3(),because Integer
becauseInteger extends
Integerextends Number.
extendsNumber. The
Number.The second
Thesecond create()
secondcreate() creates
create()creates an ArrayList<Integer>
createsananArrayList<Integer>
ArrayList<Integer>
that
that
thatcancan
canalsoalso be used
alsobebeused as a parameter,
usedasasa aparameter, but
parameter,but the
butthe third
thethird creates
thirdcreates an ArrayList<Double>,
createsananArrayList<Double>,
ArrayList<Double>,which which
whichisis
is
not
not a supertype
nota asupertype of ArrayList<Integer>.
supertypeofofArrayList<Integer>.
ArrayList<Integer>.You You must
Youmust specifically
mustspecifically note
specificallynote that
notethat if you
thatififyou changed
youchanged
changedthe the
the
last
last line
lastline to
linetoto

print3(create(2.1, 3.2, 5.3, 7.4));


print3(create(2.1, 3.2, 5.3,
print3(create(2.1, 3.2, 5.3, 7.4));
7.4));

then
then things
then things would
things would work.
would work. The
work. The compiler
The compiler will
compiler will see
will see that
see that the
that the method
the method print3()
method print3() requires
print3() requires an
requires an
an
ArrayList<?
ArrayList<? super
ArrayList<?super Integer>
superInteger> and
Integer>and the
andthe parameters
theparameters to create()
parameterstotocreate() are
create()are boxed
areboxed to objects
boxedtotoobjects of the
objectsofofthe type
thetype
type
Double,
Double,
Double,butbut because
butbecause of the
becauseofofthe type
thetype of inferencen
typeofofinferencen between
inferencenbetween Double
betweenDouble and
Doubleand Integer,
andInteger, the
Integer,the compiler
thecompiler
compiler
will
will create
willcreate an ArrayList<Number>.
createananArrayList<Number>.
ArrayList<Number>.

Download free eBooks at bookboon.com


114
114
114
114
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Lambda
lambda expressions
expressIons

88 LAMBDA
LAMBDA EXPRESSIONS
EXPRESSIONS
IfIf you
you inin Java
Java wants
wants to to transfer
transfer aa method
method as as aa parameter
parameter to to another
another method,
method, this
this isis done
done
by
by means
means ofof an
an interface.
interface. An An interface
interface isis aa type
type and
and can
can specifically
specifically be
be used
used as
as aa parameter
parameter
to
to aa method.
method. Before
Before II show
show how,
how, II would
would say say aa little
little more
more about
about anonymous
anonymous classes,
classes, which
which
as
as the
the name
name says
says isis aa class
class that
that has
has no
no name.
name. II havehave already
already mentioned
mentioned anonymous
anonymous classes classes
above in connection with the iterator
above in connection with the iterator pattern. pattern.

8.1
8.1 ANONYMOUS
ANONYMOUS CLASSES
CLASSES
As
As an
an example
example II will
will use
use the
the following
following types
types that
that II have
have seen
seen on
on in
in the
the book
book Java
Java 1:
1:

package lambda;

public interface Note


{
public int getValue();
public void print();
}

Download free eBooks at bookboon.com


Click on the ad to read more
115
115
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
JAVA 4: JAVA’S CLASSES
JAVA’S TYPE
TYPE SYSTEM Lambda expressions
JAVA 4: SYSTEM
AND
AND COLLECTION CLASSES
COLLECTION CLASSES lambda
lambda expressIons
expressIons

package
package lambda;
lambda;

public
public abstract
abstract class BankNote implements
class BankNote implements Note
Note
{
{
private
private int
int value;
value;

public BankNote(int
public BankNote(int value)
value)
{
{
this.value =
this.value = value;
value;
}
}

public
public int
int getValue()
getValue()
{
{
return
return value;
value;
}
}
}
}

ItIt isis types that defines banknotes. InIn Java 1, I I also defined specific classes for Danish
It is types
types that
that defines
defines banknotes.
banknotes. In Java
Java 1,
1, I also
also defined
defined specific
specific classes
classes for
for Danish
Danish
banknotes,
banknotes, but but here
but hereI will
here II willshow
will show how
show how these
how these classes
these classes can
classes can be
can be defined
be defined as
defined as anonymous
as anonymous classes.
classes.As
anonymous classes. As
banknotes, As
anan example you can define a 50 kr. banknote as follows (where all the code are written on
an example
example youyou can
can define
define aa 50
50 kr.
kr. banknote
banknote as
as follows
follows (where
(where all
all the
the code
code are
are written
written on
on
aasingle
single line):
line):
a single line):

Note
Note n1
n1 =
= new
new Note()
Note() {
{ public
public int
int getValue()
getValue() {return
{return 50;
50; }}
public void print()
public void print() {{
System.out.println("50
System.out.println("50 kr.,
kr., Sallingsundbroen
Sallingsundbroen og
og Skarpsalling-karret");
Skarpsalling-karret"); }};
}};

An
An anonymous
Ananonymous class
classisis
anonymousclass defined
isdefined by
definedby an
byan interface
aninterface (possibly
(possiblyaaaclass),
interface(possibly class), and
class),and the
andthe syntax
syntaxisis
thesyntax istoto write
towrite
write
theinterface
the
the interfacename
interface namefollowed
name followedby
followed byparentheses:
by parentheses:
parentheses:

INote n1 =
INote n1 new INote()
= new { …
INote() { … };
};

and
and inin the
in the following
the following block
following block you
block you then
you then write
then write the
write the code
the code for
code for the
for the methods
the methods that
methods that the
that the interface
the interface
interface
and
defines.
defines.TheThe class
Theclass of the
classofofthe object
theobject in question
objectininquestion
questionhashas
hasnono name,
noname,
name,and and
andanan anonymous
ananonymous
anonymousclassclass must
classmust
must
defines.
therefore always
thereforealways
alwaysbebe defined
bedefined as part
definedasaspart of an
partofofan expression.
anexpression.
expression.
therefore

Download free eBooks at bookboon.com


116

116
116
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA
JAVA
AND 4:
4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND COLLECTION CLASSES
COLLECTION CLASSES lambda
lambda expressIons
expressIons
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Lambda
lambdaexpressions
expressIons

Anonymous
Anonymous classes
classes are
are suitable
suitable and can
and can simplify
simplify the
the code
code inin situations
situations in in which
which you
you only
only
Anonymous
Anonymousclasses classesarearesuitable
suitableandandcancansimplify
simplifythethecode
codeininsituations
situationsininwhichwhichyouyouonly
only
needs
needs aa single
single object
object of
of aa particular
particular type.
type. If
If the
the job
job had
had anything
anything to
to do
do with
with banknotes,
banknotes, it
needs
needsaasingle
singleobject
objectofofaaparticular
particulartype.
type.IfIfthe
thejob
jobhad
hadanything
anythingtotodo dowith banknotes,itit
withbanknotes, it
would
would hardly
hardly be
be the
the case
case and
and the
the above
above and
and the
the following
following examples
examples are
are also
also intended
intended merely
merely
would
wouldhardly
hardlybe bethe
thecase
caseand andthe
theabove
aboveand
andthe thefollowing
followingexamples
examplesare arealsoalsointended
intendedmerely
merely
to
to show
show the
the syntax.
syntax. Anonymous
Anonymous classes
classes is
is most
most justified
justified in
in those
those cases
cases where
where the
the interface
interface
totoshow
showthe thesyntax.
syntax.Anonymous
Anonymousclasses classesisismost
mostjustified
justifiedininthose
thosecases
caseswherewherethetheinterface
interface
is
is used
used to
to define
define aa few
few or
or perhaps
perhaps only
only one
one method.
method. The
The advantage
advantage is
is of
of course
course that
that in aa
isisused
usedtotodefine
defineaafew fewororperhaps
perhapsonly
onlyone
onemethod.
method.The Theadvantage
advantageisisofofcourse thatinin
coursethat inaa
program
program –
– and
and especially
especially aa GUI
GUI program
program –
– you
you do
do not
not has
has to
to write
write aa series
series of
of simple
simple classes
classes
program
program––and andespecially
especiallyaaGUI GUIprogram
program––you youdodonot
nothas
hastotowrite
writeaaseries
seriesofofsimple
simpleclasses
classes
that
that do
do other
other than
than to
to implement
implement aa single
single method,
method, but
but there
there is
is also
also aa disadvantage,
disadvantage, as the
that
thatdo
doother
otherthanthantotoimplement
implementaasingle singlemethod,
method,but butthere
thereisisalso disadvantage,asas
alsoaadisadvantage, the
asthe
the
code
code easily
easily becomes
becomes difficult
difficult to
to read
read and
and even
even more
more difficult
difficult to
to write
write correct.
correct. The
The last
last you
you
code
codeeasily
easilybecomes
becomesdifficult
difficulttotoread
readandandeven
evenmore
moredifficult
difficulttotowrite
writecorrect.
correct.The
Thelast
lastyou
you
can
can help
help aa little
little by
by not
not writting
writting the
the code
code on
on aa single
single line:
line:
can
canhelp
helpaalittle
littleby
bynotnotwritting
writtingthethecode
codeon onaasingle
singleline:
line:
Note
Note n2 n2 =
= new
new Note()
Note()
Note n2 = new Note()
{
{
{
public
public int
int getValue()
getValue()
public int getValue()
{
{
{
return
return 100;
100;
return 100;
}
}
}

public
public void
void print()
print()
public void print()
{
{
{
System.out.println("100
System.out.println("100 kr.,
kr., Den
Den gamle
gamle Lillebæltsbro
Lillebæltsbro og
og Hindsgavl-dolken");
Hindsgavl-dolken");
System.out.println("100 kr., Den gamle Lillebæltsbro og Hindsgavl-dolken");
}
}
}
};
};
};

ItIt
It isissomething
somethingmore morereadable,
readable,but butcomparing
comparingitit with
withthe
thefact
factthat
thatan
ananonymous
anonymousclass class
It isis something
something moremore readable,
readable, butbut comparing
comparing itit with
with the
the fact
fact that
that an
an anonymous
anonymous classclass
always
alwaysoccur
always occurinin
inan
anexpression,
expression,andandinin
inmost
mostcases
casesitit
itwill
willbe
bean
anassignment
assignmentasas
asabove
aboveoror
orasas
asaa
always occur in an expression, and in most cases it will be an assignment as above or as aa
occur an expression, and most cases will be an assignment above
parameter
parameter
parameter totoaaamethod,
method,ititisisclear
clearthat
thatyou
youfast
fastends
endsout
outwith
withcode
codewhich
whichisishard
hardtotoread.
read.
parameter to to a method,
method, it
it is
is clear
clear that
that you
you fast
fast ends
ends out
out with
with code
code which
which is
is hard
hard to
to read.
read.
ItIt
Itisis
is exactly
exactly
exactly what
what
what the
the
thelambda
lambda
lambda expression
expression
expression should
should
should do
do
do better.
better.
better.
It is exactly what the lambda expression should do better.

Below
Below
Below isisanother
anotherexample
exampleofofan
ananonymous
anonymousclass,
class,but
butthis
thistime
timethe
theclass
classisisdefined
definedon
onthe
the
Below is is another
another example
example of
of an
an anonymous
anonymous class,
class, but
but this
this time
time the
the class
class is
is defined
defined on
on the
the
basis
basisofof
basis ofthetheabstract
the abstractclass
abstract classBankNote:
class BankNote:
BankNote:
basis of the abstract class BankNote:
Note
Note n3
n3 =
= new
new BankNote(200)
BankNote(200) {
{ public
public void
void print()
print() {
{
Note n3 = new BankNote(200) { public void print() {
System.out.println("200 kr.,
System.out.println("200 kr., Knippelsbro
Knippelsbro og
og bælteplade fra Langstrup");
bælteplade fra Langstrup"); }};
}};
System.out.println("200 kr., Knippelsbro og bælteplade fra Langstrup"); }};

The
The
The syntax
syntax
syntax isis
isessentially
essentially
essentially the
the
the same,
same,
same, but
but
but the
the
the example
example
example should
should
should show
show
showthat
that
thatyou
you
you can
can
canpass
pass
passvalues
values
values
The
totothesyntax is essentially
constructor, and thethe same,
anonymous but the
class example
only should
needs to show that
implement you
the can pass
abstract values
methods
to the
the constructor,
constructor, and
and the
the anonymous
anonymous class
class only
only needs
needs to
to implement
implement the
the abstract
abstract methods
methods
ofto
of
of
theclass
the
the
constructor,
classBankNote. andBelow
BankNote.
the anonymous
Below isisaaathird
third
class only needs to implement the abstract methods
example:
example:
of the class BankNote. Below is a third example:
the class BankNote. Below is third example:
Note
Note n4
n4 =
= new
new BankNote(500)
BankNote(500) {
{
Note n4 = new BankNote(500) {
public void print()
public void print()
public void print()
{
{
{
System.out.println(
System.out.println(
System.out.println(
"500
"500 kr.,
kr., Dronning
Dronning Alexandrines
Alexandrines bro
bro og
og bronzespanden
bronzespanden fra
fra Keldby");
Keldby");
"500 kr., Dronning Alexandrines bro og bronzespanden fra Keldby");
}
}
}
};
};
};

Download free eBooks at bookboon.com


117
117
117
117
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Lambda
lambda expressions
expressIons

Below is a method that has Note objects as parameters:

private static void print(Note … notes)


{
int sum = 0;
for (Note n : notes)
{
sum += n.getValue();
n.print();
}
System.out.println("Value: " + sum);
}

The method is simple and does nothing but print the objects (performs the method print())
and the sum of their values. The parameter type is defined by an interface and the method
knowns what this interface tells, but the actual parameters must naturally be objects created
on the basis of concrete classes. Below is an example of calling the method, and you will
primarily notice that one of the parameters are defined as an object of an anonymous class
written directly in the call of the method:

print(n1, n2, n3, n4, new BankNote(1000) { public void print() {


System.out.println("1000 kr., Storebæltsbroen og Solvognen"); } } );

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57


Download free eBooks at bookboon.com
Click on the ad to read more
118
118
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES lambda expressIons
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Lambda
lambdaexpressions
expressIons

8.2 METHODS AS PARAMETERS


8.2
In
METHODS
8.2other
METHODS AS PARAMETERS
programmingASlanguages,
PARAMETERS
such as C and C ++ you can transfer references to
InIn other
methods programming
other as parameters to
programming languages, such
such asasThis
another method.
languages, CC andcan Cnot
and C ++ beyou
++ donecan
you transfer
directly
can references
in Java,
transfer and ittois
references to
methods
methodsasto
necessary asparameters
transfer
parameters totoanother
a method method.
method.This
encapsulated
another in
Thisancan not
notbe
object.
can bedone
The directly
objects
done ininway
in this
directly Java,
Java, and
andititisis
transfered
necessary
as
necessary tototransfer
a parameter transferaamethod
to a method
method is encapsulated
usually defined
encapsulated ininby
an object.
anan The
Theobjects
interface.
object. ininthis
Consider
objects as
thisanway transfered
example,
way the
transfered
asasaaparameter
following
parameter totoaamethod
interface, which
method isisusually
defines defined
a method
usually defined by
that an
byhas interface.
anan Consider
int parameter
interface. andasas
Consider ananexample,
returns the
a boolean:
example, the
following
followinginterface,
interface,which
whichdefines
definesaamethod
methodthat thathas
hasananint
intparameter
parameterandandreturns
returnsaaboolean:
boolean:
interface ISelector
{interface ISelector
{public boolean select(int t);
} public boolean select(int t);
}
Below is a method that prints the elements of an int array, but only the elements where
an ISelector
Below
Below object
methodreturns
isisaamethod that true:the
thatprints
prints theelements
elementsofofan
anint
intarray,
array,but
butonly
onlythe
theelements
elementswhere
where
anISelector
an ISelectorobject
objectreturns
returnstrue:
true:
private static void print(int[] arr, ISelector s)
{private static void print(int[] arr, ISelector s)
{for (int t : arr) if (s.select(t)) System.out.print(t + " ");
System.out.println();
for (int t : arr) if (s.select(t)) System.out.print(t + " ");
} System.out.println();
}
It is thus an example of how to transfer a method select() as a parameter to another method.
ItSuppose
Itisisthus
thusan
anexample
there ofofhow
are defined
example totofollowing
the
how transfer
transferaaarray:
method
methodselect()
select()asasaaparameter
parametertotoanother
anothermethod.
method.
Suppose
Supposetherethereare
aredefined
definedthethefollowing
followingarray:
array:
int[] arr = new int[120];
for (int
int[] arri == new
0; iint[120];
< arr.length; ++i) arr[i] = i;
for (int i = 0; i < arr.length; ++i) arr[i] = i;
and assume that you want to use the above print() method to print all 2-digit numbers.
You
and must
andassume
assumethenthatsend
that youan
you wantISelector
want useobject
totouse the as a print()
theabove
above parameter, and totocreate
print()method
method print such
printall an object,
all2-digit
2-digit you
numbers.
numbers.
must
You havethen
Youmust
must athen
class:
send
sendananISelector
ISelectorobject
objectasasaaparameter,
parameter,and
andtotocreate
createsuch
suchananobject,
object,you
you
must
musthave
haveaaclass:
class:
class Select2 implements ISelector
{class Select2 implements ISelector
{public boolean select(int t)
{public boolean select(int t)
{return t > 9 && t < 100;
} return t > 9 && t < 100;
}}
}
You
You can
can then
then print
print the
the numbers
numbers as
as follows:
follows:
You can then print the numbers as follows:
print(arr, new Select2());
print(arr, new Select2());

119 at bookboon.com
Download free eBooks
119
119
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND
JAVA
JAVA 4:
4: JAVA’S
COLLECTION
4: JAVA’S TYPE
JAVA’S TYPE
TYPE SYSTEM
CLASSES
SYSTEM
SYSTEM lambda expressIons
AND COLLECTION CLASSES lambda expressIons
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES
AND COLLECTION CLASSES lambda
Lambda expressIons
lambda expressions
expressIons

If
If instead
instead you
you want
want to
to print
print all
all prime
prime numbers,
numbers, you
you can
can write
write the
the following
following class
class that
that
IfIf
If instead
instead
instead
implements
you
you
you
the
want
want
want to
to
to
interface
print
print
print all
all
all
ISelector:
prime
prime
prime numbers,
numbers,
numbers, you
you
you can
can
can write
write
write the
the
the following
following
following class
class
class that
that
that
implements
implements the the
the interface
interface ISelector:
ISelector:
implements
implements the interface
interface ISelector:
ISelector:
class SelectPrimes implements ISelector
class
class SelectPrimes implements ISelector
class SelectPrimes
{ SelectPrimes implements
implements ISelector
ISelector
{
{
{ public boolean select(int t)
public
public boolean select(int t)
public boolean
{ boolean select(int
select(int t) t)
{
{
{ if (t == 2 || t == 3 || t == 5 || t == 7) return true;
if
if (t == 2 || t == 3 || t == 5 || t == 7) return true;
if (t
(t ==
== 11
< 2
2 ||
|| t
t ==
== 23
% ||
3 == t
t ==
|| 0) == 5
5 || t
t ==
== 7)
||false;
return 7) return
return true;
true;
if
if (t
(t <
< 11
11 ||
|| t
t %
% 2
2 ==
== 0)
0) return
return false;
false;
if (t
for < 11
(int n =||3,t m% =2 (int)Math.sqrt(t)
== 0) return false;
+ 1; n <= m; n += 2) if (t % n == 0)
for
for (int
(int n
n = 3, m = (int)Math.sqrt(t) + 1; n <= m; n += 2) if (t % n == 0)
for n == 3,
(int false;
return 3, mm == (int)Math.sqrt(t)
(int)Math.sqrt(t) + + 1;
1; n
n <=
<= m;
m; n
n +=
+= 2)
2) if
if (t
(t %
% n
n ==
== 0)
0)
return
return false;
false;
returntrue;
return false;
return true;
} return
return true;
true;
}
}}}
}
}
}

and
and then
then you
you can
can print
print the
the primes
primes with
with the
the following
following statement:
statement:
and
and then you can print the primes with the following statement:
and then
then you
you can
can print
print the
the primes
primes with
with the
the following
following statement:
statement:
print(arr, new SelectPrimes());
print(arr,
print(arr, new SelectPrimes());
print(arr, new
new SelectPrimes());
SelectPrimes());

It is clear that in the situation where you have to transfer a method as a parameter to
ItIt
It
It isis
is
is
clear
clear
clear
clear
that
that
that
that
in
in
in
in
the
the
the
the
situation
situation
situation
situation
where
where
where
where
you
you
you
you
have
have
have
have
to
to
to
to
transfer
transfer
transfer
transfer aaaa method
method
method
method
as
as
as
as aaaa parameter
parameter
parameter
parameter
to
to
to
to
another
another method
method it
it is
is obvious
obvious to
to use
use an
an anonymous
anonymous class.
class. If
If you
you again
again wish
wish to
to print
print all
all
another
another
another method
method it
it
method ityou is
is obvious
obvious
is can
obvious to
to use
use
to use an
an anonymous
anonymous
an anonymous class.
class. If
If you
you again
again wish
wish to
to
class. If you again wish to print all print
print all
all
2-digit
2-digit numbers,
numbers, you can use
use the
the following
following statement:
statement:
2-digit numbers,
2-digit
2-digit numbers, you
numbers, you can
you can use
can use the
use the following
the following statement:
following statement:
statement:
print(arr, new ISelector() {
print(arr,
print(arr, new
new ISelector() {
print(arr, new ISelector()
public boolean ISelector()
select(int {
{
t) { return t > 9 && t < 100; } });
public
public boolean select(int t) { return t > 9 && t < 100; } });
public boolean select(int
boolean select(int t)
t) {
{ return
return t
t >
> 9
9 &&
&& t
t <
< 100;
100; }
} });
});

where
where
where the
the
the ISelector
ISelector
ISelector object
object
object this
this
this time
time
time isis
is defined
defined
defined on
on
on the
the
the basis
basis
basis of
of
of an
an
an anonymous
anonymous
anonymous class.
class.
class. The
The
The class
class
class
where
where the
the ISelector
ISelector object
object this
this time
time is
is defined
defined on
on the
the basis
basis of
of an
an anonymous
anonymous class.
class. The
The class
class
Select2
Select2
Select2 is
is
is then
then
then unnecessary.
unnecessary.
unnecessary. Similarly,
Similarly,
Similarly, one
one
one can
can
can print
print
print the
the
the prime
prime
prime numbers
numbers
numbers in
in
in the
the
the following
following
following way:
way:
way:
Select2 is
Select2 is then
then unnecessary.
unnecessary. Similarly,
Similarly, oneone can
can print
print the
the prime
prime numbers
numbers inin the
the following
following way:
way:
print(arr, new ISelector() {
print(arr,
print(arr, new
new ISelector() {
print(arr, new ISelector()
public boolean select(int {
ISelector() {
t)
public
public boolean select(int t)
public boolean select(int t)
{ boolean select(int t)
{
{
{ if (t == 2 || t == 3 || t == 5 || t == 7) return true;
if
if (t == 2 || t == 3 || t == 5 || t == 7) return true;
if (t
(t ==
== 11
< 2
2 ||
|| tt ==
== 23
% ||
3 == t
t ==
|| 0) == 5
5 || t
t ==
== 7)
||false;
return 7) return
return true;
true;
if
if (t < 11 || t % 2 == 0) return false;
if (t
for (t <
< 11
(int n =||
11 ||3,t
t m%
% =2 ==
== 0)
0) return
return false;
2 (int)Math.sqrt(t)
false;
+ 1; n <= m; n += 2) if (t % n == 0)
for
for (int
(int n
n = 3, m = (int)Math.sqrt(t) + 1; n <= m; n += 2) if (t % n == 0)
for n == 3,
(int false;
return 3, mm == (int)Math.sqrt(t)
(int)Math.sqrt(t) ++ 1;
1; nn <=
<= m;
m; n
n +=
+= 2)
2) if
if (t
(t %
% n
n ==
== 0)
0)
return
return false;
false;
returntrue;
return false;
return true;
} return
return true;
true;
}
}
}
});
});
});
});

but
but
but here
here
here are
are
are the
the
the benefits
benefits
benefits are
are
are not
not
not as
as
as big
big
big as
as
as this
this
this leads
leads
leads to
to
to code
code
code that
that
that isis
is hard
hard
hard to
to
to read.
read.
read. IfIf
If you
you
you
but
but here
here are
are the
the benefits
benefits are
are not
not as
as big
big as
as this
this leads
leads to
to code
code that
that is
is hard
hard to
to read.
read. If
If you
you
want
want
want to
to
to print
print
print the
the
the 2-digit
2-digit
2-digit numbers,
numbers,
numbers, you
you
you can
can
can also
also
also use
use
use the
the
the following
following
following syntax:
syntax:
syntax:
want
want toto print
print thethe 2-digit
2-digit numbers,
numbers, youyou can
can also
also use
use the
the following
following syntax:
syntax:
print(arr, t -> t > 9 && t < 100);
print(arr,
print(arr, t
t ->
-> t
t >
> 9
9 &&
&& t
t <
< 100);
100);
print(arr, t -> t > 9 && t < 100);

Download free eBooks


120
at bookboon.com
120
120
120
120
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Lambda
lambda expressions
expressIons

ItIt isis an
an example
example ofof aa lambda
lambda expression,
expression, and
and even
even ifif itit seems
seems mysterious,
mysterious, itit isis both
both simple
simple
to
to write
write and
and read.
read. In
In its
its simplest
simplest form,
form, the
the syntax
syntax ofof aa lambda
lambda expression
expression isis

e -> expression

wherethe
where theexpression
expressiontypically
typicallydepends
dependson one,e,and
anddetermines
determinesaavalue.
value.In
Inthis
thiscase
casethe
thecompiler
compiler
knows the
knows the print()
print() method
method andand knows
knows that
that itit requires
requires an
an ISelector
ISelector object
object and
and the
the lambda
lambda
expression must
expression must therefore
therefore act
act on
on an
an int
int and
and return
return aa boolean.
boolean. Specifically,
Specifically, what
what happens
happens isis
that the
that the compiler
compiler creates
creates an
an anonymous
anonymous ISelector
ISelector object
object that
that implements
implements thethe select()
select() method
method
on the
on the basis
basis of
of the
the lambda
lambda expression.
expression.

ItIt isis also


also possible
possible to
to write
write the
the selection
selection of
of prime
prime numbers
numbers by
by means
means of
of aa lambda
lambda expression:
expression:

print(arr, t -> {
if (t == 2 || t == 3 || t == 5 || t == 7) return true;
if (t < 11 || t % 2 == 0) return false;
for (int n = 3, m = (int)Math.sqrt(t) + 1; n <= m; n += 2) if (t % n == 0)
return false;
return true;
});

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

Download free eBooks at bookboon.com


Click on the ad to read more
121
121
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
AND COLLECTION TYPE SYSTEM
SYSTEM
CLASSES lambda expressIons
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Lambda
lambda expressions
expressIons

but then you are back to a code that is hard to read, and in this case I prefer to write a
but
but then
then you
you are
are back
back to
to aa code
code that
that isis hard
hard to
to read,
read, and
and in
in this
this case
case II prefer
prefer to
to write
write aa
method:
method:
method:
public static boolean isPrime(int t)
public
{ static boolean isPrime(int t)
{ if (t == 2 || t == 3 || t == 5 || t == 7) return true;
if
if (t
(t ==
< 112 ||
|| t
t ==
% 23 ==
|| 0)
t == 5 ||false;
return t == 7) return true;
if (t < 11 || t % 2 == 0) return false;
for (int n = 3, m = (int)Math.sqrt(t) + 1; n <= m; n += 2) if (t % n == 0) return false;
for (int true;
return n = 3, m = (int)Math.sqrt(t) + 1; n <= m; n += 2) if (t % n == 0) return false;
} return true;
}

and
and then
then write:
write:
and then write:
print(arr, t -> isPrime(t));
print(arr, t -> isPrime(t));

8.3
8.3 EXAMPLES OF
EXAMPLES OF LAMBDA EXPRESSIONS
EXPRESSIONS
8.3 EXAMPLES OF LAMBDA
LAMBDA EXPRESSIONS
The following
The following examples areare intended toto show examples
examples of lambda
lambda expressions, including
including
The following examples
examples are intended
intended to show
show examples of of lambda expressions,
expressions, including
variations of
variations of the syntax.
syntax. As an
an example, II use
use a collection of
of postal codes,
codes, a collection that
that
variations of the
the syntax. As
As an example,
example, I use aa collection
collection of postal
postal codes, aa collection
collection that
III have
have shown
shown in aa previous
have shown in
previous example in
in a previous example
in this book,
example in this
book, and the
this book, and
the starting point
and the starting
point is thus the
starting point isis thus
the class:
thus the class:
class:
package lambda;
package
package lambda;
lambda;

public class Post implements Comparable<Post>


public
{ class Post implements Comparable<Post>
{ private String code; // the zip code
private
private String
String code;
city; //
// the
name zip
og code
the town
private String city; // name og the town

public Post(String code, String city)


public
{ Post(String code, String city)
{ this.code = code;
this.code
this.city =
= code;
city;
} this.city = city;
}

public String getCode()


public
{ String getCode()
{ return code;
} return code;
}

public String getCity()


public
{ String getCity()
{ return city;
} return city;
}

Download free eBooks at bookboon.com


122
122
122
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
JAVA CLASSES lambda expressIons
AND 4: JAVA’S TYPECLASSES
COLLECTION SYSTEM Lambda expressions
AND COLLECTION CLASSES lambda expressIons

public void setCity(String city)


{
public void setCity(String city)
{ this.city = city;
}
this.city = city;
}
public String toString()
{
public String toString()
{ return code + " " + city;
}
return code + " " + city;
}
public boolean equals(Object obj)
{
public boolean equals(Object obj)
{ if (obj == null) return false;
ifif (obj
(getClass()
== null)==return
obj.getClass())
false; return ((Post)obj).getCode().equals(code);
ifreturn false; == obj.getClass()) return ((Post)obj).getCode().equals(code);
(getClass()
}
return false;
}
public int hashCode()
{
public int hashCode()
{ return code.hashCode();
}
return code.hashCode();
}
public int compareTo(Post post)
{
public int compareTo(Post post)
{ return code.compareTo(post.getCode());
}
return code.compareTo(post.getCode());
}
}
The
The class
class has
has changed
changed aa bit,
bit, and
and you
you should
should especially
especially note
note that
that the
the class
class overrides
overrides equals()
equals()
The class
where has
where objects changed
objects solely a
solely are bit, and
are compared you
compared on should
on there especially
there zip
zip code, note
code, and that
and the the
the class class overrides
class implements
implements the equals()
the interface
interface
where objects solely so
Comparable<Post>
Comparable<Post> arethat
so compared
that the on there
the objects
objects are zip code, only
are arranged
arranged and the
only by class
by the
the zipimplements
zip codes. the interface
codes.
Comparable<Post> so that the objects are arranged only by the zip codes.
The
The class
class Postcodes
Postcodes isis aa collection
collection of
of Danish
Danish postal
postal codes,
codes, andand the
the class
class isis in
in many
many waysways also
also
The
the class
the same Postcodes
same as is
as before, a
before, wherecollection
where the of Danish
the objects
objects are postal
are created codes,
created based
based on and the
on the class
the nested is in
nested class many
class Data. ways
Data. The also
The class
class
the same as before,
isis expanded
expanded with aawhere
with few the objects
few methods,
methods, andare
and created
the
the one based on
one iterator
iterator the nestedThe
isis removed.
removed. class
The Data.
class
class asThe
isis as class
follows:
follows:
is expanded with a few methods, and the one iterator is removed. The class is as follows:
package lambda;
package lambda;
import java.util.*;
import java.util.*;
public class Postcodes implements Iterable<Post>
{
public class Postcodes implements Iterable<Post>
{ private ArrayList<Post> list = new ArrayList();
private ArrayList<Post> list = new ArrayList();

Download free eBooks at bookboon.com


123
123
123
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Lambda expressions
AND COLLECTION CLASSES lambda expressIons

public Postcodes()
{
Data data = new Data();
for (int i = 0; i < data.length(); ++i)
list.add(new Post(data.getCode(i), data.getCity(i)));
}

public int length()


{
return list.size();
}

public Post get(int n)


{
return list.get(n);
}

public Post get(String code) throws Exception


{
for (Post p : list) if (p.getCode().equals(p)) return p;
throw new Exception("Zip code " + code + " not found");
}

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

Download free eBooks at bookboon.com


Click on the ad to read more
124
124
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Lambda expressions
AND COLLECTION CLASSES lambda expressIons

public Iterator<Post> iterator()


{
return list.iterator();
}

public static class Data


{

}
}

The
The program
program defines
defines the
the following
following object,
object, that
that II will
will use
use in
in the
the following:
following:

private static Postcodes post = new Postcodes();

II will
will start
start with
with aa search
search method
method that
that can
can search
search in
in the
the collection
collection post.
post. The
The method
method should
should
have two
have two parameters,
parameters, where
where the
the one
one isis the
the zip
zip codes,
codes, while
while the
the other
other isis the
the search
search criteria,
criteria,
which isis aa method
which method that
that can
can select
select the
the objects
objects to
to be
be included.
included. Such
Such aa method
method could
could bebe
defined with
defined with an
an interface
interface in
in the
the following
following way:way:

public interface SearchPostcodes


{
public boolean select(Post p);
}

and thus
and thus in
in the
the same
same manner
manner asas II before
before defined
defined ISelector.
ISelector. However,
However, itit isis unnecessary
unnecessary for
for the
the
Java API
Java API defines
defines aa generic
generic interface
interface Predicate<T>
Predicate<T> for
for this
this purpose
purpose and
and method
method ofof searching
searching
can then
can then be
be defined
defined as
as follows:
follows:

private static ArrayList<Post> search(Postcodes post, Predicate<Post> select)


{
ArrayList<Post> list = new ArrayList();
for (Post p : post) if (select.test(p)) list.add(p);
return list;
}

The predicate
The predicate isis called
called select,
select, and
and itit has
has aa method
method called
called test()
test() and
and parameter
parameter of
of the
the type
type
Post. This
Post. This method
method returns
returns true
true ifif aa zip
zip code
code meet
meet the
the criterion.
criterion.

Download free eBooks at bookboon.com


125
125
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Lambda
lambdaexpressions
expressIons

If,If,for
forexample
exampleyou
youwant
wanttotofind
findall
allthe
thezip
zipcodes
codeswhere
wherethe
thecity
cityname
namestarts
startswith
with“Ski”,
“Ski”,
you
youcan canwrite:
write:

private static void test03()


{
print(search(post, p -> p.getCity().startsWith("Ski")));
}

private static void print(ArrayList<Post> list)


{
for (Post p : list) System.out.println(p);
}

As
Asanother
anotherexample,
example,the
thefollowing
followingmethod
methodfinds
findsall
allzip
zipcodes
codesthat
thatstart
startwith
with55and
andwhere
where
the
thecity
cityname
nameincludes
includesthe
thetext
text“køb”,
“køb”,but
butsosothat
thatthere
thereisisno
nodistinction
distinctionbetween
betweenuppercase
uppercase
and
andlowercase:
lowercase:

private static void test04()


{
print(search(post,
p -> p.getCode().startsWith("5") && p.getCity().toLowerCase().contains("køb")));
}

The
Theabove
abovesearch
searchmethod
methodreturns
returnsananArrayList<Post>
ArrayList<Post>and
andininrelation
relationtotolambda
lambdaexpressions
expressions
the
the important parameter is Predicate<Post>. However, there are other options, and
important parameter is Predicate<Post>. However, there are other options, and the
the
following search method has also a Consumer<Post> as a parameter:
following search method has also a Consumer<Post> as a parameter:

private static ArrayList<Post> search(Postcodes post, Predicate<Post> tester,


Consumer<Post> action)
{
ArrayList<Post> list = new ArrayList();
for (Post p : post) if (tester.test(p))
{
action.accept(p);
list.add(p);
}
return list;
}

AAConsumer<Post>
Consumer<Post>objectobjecthas
hasaamethod
methodcalled
calledaccept(),
accept(),that
thathas
hasaaPost
Postobject
objectasasaaparameter.
parameter.
Theidea
The ideaisisthat
thatyou
youthen
thencan
canmodify
modifythe
theobjects
objectsbefore
beforethey
theyare
areadded
addedtotothe
thelist.
list.As
Asan
an
example,chooses
example, choosesthe
themethod
methodbelow
belowthat
thatselects
selectsall
allzip
zipcodes
codeswhere
wherethethecity
cityname
namestates
stateswith
with
“Ski”,but
“Ski”, butbefore
beforethe
theobjects
objectsare
areplaced
placedininthe
thelist,
list,the
thecity
cityname
nameisisconverted
convertedtotouppercase:
uppercase:

Download free eBooks at bookboon.com


126
126
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Lambda expressions
AND COLLECTION CLASSES lambda expressIons

private static void test05()


{
print(search(post, p -> p.getCity().startsWith("Ski"),
p -> p.setCity(p.getCity().toUpperCase())));
}

Thelast
The lastsearch
searchmethod
methodhadhada aparameter
parameterofoftype
typeConsumer<Post>,
Consumer<Post>,which
whichhas
hasa avoid
voidmethod
method
accept(),which
accept(), whichhas
hasa aPost
Postobject
objectasasa aparameter.
parameter.

There isis a a generic


There generic interface
interface Function,
Function, which
which isis parameterized
parameterized with
with the
the two
two types,
types, that
that
definesa amethod
defines methodapply(),
apply(),and
andwherein
whereinthethetwo
twoparameters
parametersdenotes
denotesrespectively
respectivelythe
thetype
typeofof
a aparameter
parametertotoapply()
apply()while
whilethe
theother
otherisisthe
thetype
typeofofa areturn
returnvalue.
value.Below
Belowisisanother
anothersearch
search
function,there
function, thereasasparameters
parametershas hasa aPredicate<Post>
Predicate<Post>and anda aFunction<Post,
Function<Post,Post>.
Post>.The
Themethod
method
hasa aPost
has Postobject
objectasasparameter,
parameter,andandreturns
returnsthe
thesame
sameobject
objectagain,
again,but
butafter
afterthe
themethod
method
apply()isisused
apply() usedononthetheobject:
object:
360°
private static ArrayList<Post> search1(Postcodes
post, Predicate<Post> tester,

{
Function<Post, Post> func)

ArrayList<Post> list = new ArrayList();


thinking .

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discoverfree
Download theeBooks
truth atatbookboon.com
www.deloitte.ca/careers
Click on the ad to read more
127
127
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Lambda expressions
AND COLLECTION CLASSES lambda expressIons
AND COLLECTION CLASSES lambda expressIons

for (Post p : post) if (tester.test(p)) list.add(func.apply(p));


for (Post p : post) if (tester.test(p)) list.add(func.apply(p));
return list;
return list;
}
}

You
You should note that this time II have called the method search1() and not the search(). The
You should
should note
note that
that this
this time
time I have
have called
called the
the method
method search1()
search1() and
and not
not the
the search().
search(). The
The
reason
reason isis that otherwise the compiler can not distinguish between this search method and
reason is that otherwise the compiler can not distinguish between this search method and
that otherwise the compiler can not distinguish between this search method and
the
the previous, as there will not be overloaded on the return value of aa method. Below isis an
the previous, as there will not be overloaded on the return value of a method. Below is an
previous, as there will not be overloaded on the return value of method. Below an
example
example which
which uses
uses the
the above
above search
search method:
method:
example which uses the above search method:

private static void test06()


private static void test06()
{
{
print(search1(post, p -> p.getCity().startsWith("Ski"),
print(search1(post, p -> p.getCity().startsWith("Ski"),
p -> new Post(p.getCode(), p.getCity().toUpperCase())));
p -> new Post(p.getCode(), p.getCity().toUpperCase())));
}
}

The
The difference isis that this test method returns other objects than the previous test method
The difference
difference is that
that this
this test
test method
method returns
returns other
other objects
objects than
than the
the previous
previous test
test method
method
that
that modifieds
modifieds the
the original
original collection.
collection.
that modifieds the original collection.
All
All of these options can be combined:
All of
of these
these options
options can
can be
be combined:
combined:

private static <X, Y> ArrayList<Y> search(Iterable<X> source, Predicate<X> tester,


private static <X, Y> ArrayList<Y> search(Iterable<X> source, Predicate<X> tester,
Function <X, Y> mapper, Consumer<Y> action)
Function <X, Y> mapper, Consumer<Y> action)
{
{
ArrayList<Y> list = new ArrayList();
ArrayList<Y> list = new ArrayList();
for (X x : source)
for (X x : source)
if (tester.test(x))
if (tester.test(x))
{
{
Y y = mapper.apply(x);
Y y = mapper.apply(x);
action.accept(y);
action.accept(y);
list.add(y);
list.add(y);
}
}
return list;
return list;
}
}

It
It is aa generic method, which is parameterized with two types XX and Y, and it returns an
It is
is a generic
generic method,
method, which
which is is parameterized
parameterized withwith two two types
types X and
and Y,
Y, and
and it
it returns
returns an
an
ArrayList<Y>.
ArrayList<Y>. The
The method
method can
can be
be applied
applied to
to any
any collection
collection of
of objects
objects of
of the
the type
type XX that
that
ArrayList<Y>. The method can be applied to any collection of objects of the type X that
implements
implements the iterator pattern. For the objects that are selected by the predicate, the
implements the the iterator
iterator pattern.
pattern. ForFor the
the objects
objects thatthat areare selected
selected by by the
the predicate,
predicate, thethe
method
method creates
creates aa new
new object
object of
of the
the type
type Y,
Y, and
and itit isis treated
treated with
with the
the Consumer<Y>
Consumer<Y> object
object
method creates a new object of the type Y, and it is treated with the Consumer<Y> object
before
before it isis saved in the result. As an example, the following method selects the zip codes
before it it is saved
saved inin the
the result.
result. As
As anan example,
example, thethe following
following method
method selects
selects the
the zip
zip codes
codes
where
where the code begins with “78”. These objects are returned as aa string, but before the city
where the code begins with “78”. These objects are returned as a string, but before the city
the code begins with “78”. These objects are returned as string, but before the city
name
name added
added to
to aa StringBuilder:
StringBuilder:
name added to a StringBuilder:

Download free eBooks at bookboon.com


128
128
128
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Lambda expressions
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES lambda expressIons
AND COLLECTION CLASSES lambda expressIons

private static void test07()


private static void test07()
{
{
StringBuilder builder = new StringBuilder();
StringBuilder builder = new StringBuilder();
Collection<String> collection = search(post, p -> p.getCode().startsWith("78"),
Collection<String> collection = search(post, p -> p.getCode().startsWith("78"),
p -> p.toString(), s -> builder.append(s + ", "));
p -> p.toString(), s -> builder.append(s + ", "));
for (String s : collection) System.out.println(s);
for (String s : collection) System.out.println(s);
System.out.println(builder.toString());
System.out.println(builder.toString());
}
}

8.4
8.4 JAVA
8.4 JAVA FUNCTIONAL
JAVAFUNCTIONAL INTERFACES
FUNCTIONALINTERFACES
INTERFACES
InIn the
Inthe section
thesection above
aboveI IIhave
sectionabove have used
haveused the
usedthe interfaces
theinterfaces
interfaces

---- Predicate<T>
Predicate<T>
Predicate<T>
---- Consumer<T>
Consumer<T>
Consumer<T>
---- Function<T,
Function<T, R>
Function<T,R>
R>

that
that are
thatare generic
aregeneric interfaces,
genericinterfaces, all
allofof
interfaces,all which
ofwhich defines
definesaaasingle
whichdefines single method,
singlemethod,
method,and and they
andthey are
theyare actually
areactually defined
actuallydefined
defined
toto be used by a lambda expression. They are defined in java.util.function,
to be used by a lambda expression. They are defined in java.util.function, and thereare
be used by a lambda expression. They are defined in java.util.function, and
and there
there are
are
defined
defined some
definedsome more
somemore functional
morefunctional interfaces
functionalinterfaces (next
interfaces(next
(next50)50) and
50)and you
andyou
youareare encouraged
areencouraged to investigate
encouragedtotoinvestigate
investigate
what
what interfaces
whatinterfaces are
interfacesare defined.
aredefined.
defined.

The
The functional
Thefunctional interfaces
functionalinterfaces looks
interfaceslooks like
lookslike each
likeeach other,
eachother, and
other,and each
andeach interface
eachinterface has
hasaaasingle
interfacehas single abstract
singleabstract method,
abstractmethod,
method,
called
called the
the functional
functional method
method for
for that
that functional
functional interface.
interface. The
The interfaces
interfaces are
are
called the functional method for that functional interface. The interfaces are as mentioned as
as mentioned
mentioned
defined
definedtoto
defined tobebe used
beused with
usedwith lambda
withlambda expressions,
lambdaexpressions, but
expressions,but they
butthey are
theyare general
aregeneral purpose
generalpurpose interfaces,
purposeinterfaces, and
interfaces,and
and
are
are available
areavailable to be
availabletotobe used
beused
usedby by user
byuser code
usercode anywhere.
codeanywhere.
anywhere.Of Of course
Ofcourse they
coursethey
theydodo not
donot identify
notidentify all
identifyall possible
allpossible
possible
method
method prototypes
methodprototypes to which
prototypestotowhich lambda
whichlambda expressions
lambdaexpressions might
expressionsmight
mightbe be used,
beused, but
used,but you
butyou should
youshould
shouldbe be aware
beaware
aware
that
that other
other Java
Java packages
packages also
also define
define functional
functional interfaces.
interfaces.
that other Java packages also define functional interfaces.

8.5
8.5 EVENT
8.5 EVENT HANDLERS
EVENTHANDLERS
HANDLERS
Probably
Probably
Probablythe the most
themost important
mostimportant
importantuse use
useofof lambda
oflambda expressions
lambdaexpressions
expressionsareare attaching
areattaching event
attachingevent handlers
eventhandlers
handlersfor for
for
components
components in
componentsininaaGUI a GUI program,
GUIprogram,
program,and and in fact
andininfact I have
factI Ihave already
havealready used
alreadyused lambda
usedlambda expressions
lambdaexpressions in
expressionsininGUIGUI
GUI
programs
programs several
programsseveral times.
severaltimes. I have
times.I Ihave added
haveadded a
addedaaclassclass to this
classtotothis project,
thisproject, called
project,called Window,
calledWindow,
Window,and and it opens
andititopens
opens
the
the same window as in the first example in the book Java 2. The
the same window as in the first example in the book Java 2. The only change is thatthe
same window as in the first example in the book Java 2. The only
only change
change is
is that
that the
the
event
event handlers
handlers are
are defined
defined in
in a a different
different way.
way. The
The window
window has
has two
two buttons.
buttons.
event handlers are defined in a different way. The window has two buttons. One that erases One
One that
that erases
erases
the
the contents
contentsofof
thecontents ofaaalist
list box,
listbox, and
box,and
andthe the only
theonly thing
onlything
thingthatthat must
thatmust happen
happenisis
musthappen that
isthat the
thatthe model
themodel
modelmustmust
mustbe be
be
cleared.
cleared. It can
cleared.ItItcan
canbebe written
bewritten directly,
writtendirectly, using
directly,using a lambda
usingaalambda expression:
lambdaexpression:
expression:
cmdClr.addActionListener(e -> model.clear());
cmdClr.addActionListener(e -> model.clear());

The
The notation
notation isis
The notation appropriate
appropriate ifif
is appropriate the
if the event
the event handler
event handler simply
handler simply consists
consists ofof
simply consists of aaa single
single statement
single statement
statement
oror
or perhaps several quite simple statements. If the event handler is more complex, itit
perhaps
perhaps several
several quite
quite simple
simple statements.
statements. If
If the
the event
event handler
handler isis more
more complex,
complex, it isis
is
recommended
recommended to
recommendedtotowrite write a method:
writeaamethod:
method:

Download free eBooks at bookboon.com


129
129
129
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Lambda expressions
AND COLLECTION CLASSES lambda expressIons
AND COLLECTION CLASSES lambda expressIons

private
private void
void addName(ActionEvent
addName(ActionEvent e)
e)
{
{
String
String name
name =
= txtName.getText().trim();
txtName.getText().trim();
if
if (name.length() >
(name.length() > 0)
0)
{
{
model.addElement(name);
model.addElement(name);
txtName.setText("");
txtName.setText("");
txtName.requestFocus();
txtName.requestFocus();
}
}
}
}

It
It must be a void method, and itit must have aa parameter of the type ActionEvent, but
It must
must be
be aa void
void method,
method, and
and it must
must have
have a parameter
parameter of
of the
the type
type ActionEvent,
ActionEvent, but
but
otherwise
otherwise itit is
is aa rather
rather straightforward
straightforward method.
method. You
You can
can then
then write
write the
the event
event handler
handler as
as
otherwise it is a rather straightforward method. You can then write the event handler as

cmdAdd.addActionListener(e -> addName(e));


cmdAdd.addActionListener(e -> addName(e));

Java,
Java, however, has a different syntax for the same thing:
Java, however,
however, has
has aa different
different syntax
syntax for
for the
the same
same thing:
thing:

cmdAdd.addActionListener(this::addName);
cmdAdd.addActionListener(this::addName);

There
There are no benefits of the last writing, and one can even say that itit is yet another use of
There are
are no
no benefits
benefits of
of the
the last
last writing,
writing, and
and one
one can
can even
even say
say that
that it is
is yet
yet another
another use
use of
of
the
the word
word this,
this, but
but once
once you’ve
you’ve used
used it
it for
for a
a while,
while, the
the syntax
syntax is
is sensible
sensible enough.
enough.
the word this, but once you’ve used it for a while, the syntax is sensible enough.

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

Download free eBooks at bookboon.com


Click on the ad to read more
130
130
130
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection classes

9 COLLECTION CLASSES
A collection class is a container for objects, and a good example is the type ArrayList, which
is discussed and used many times in the previous books. A collection class is a little more
than just a container for objects since the class also provides a number of methods available
which are used to manipulate the container’s objects. Java has many other collection classes
than ArrayList, and they differ in terms of how they are implemented and store their objects,
as well as the services they provides in the form of methods. Overall reflects these collection
classes the tasks that typically occur in programs to manipulate a family of objects.

It should immediately be said that the goal of this chapter is to give an overview of the
collection classes, which classes exist and what they can be used for, but it is not a detailed
review of the collection classes and how they work. However, it is the subject of the book
Java 17.

Java collection classes are contained in a framework, which basically consists of three things:

1. abstract classes and interfaces that defines the various collection classes and their
main characteristics
2. concrete classes that implements the interfaces in the framework
3. algorithms that are methods for a number of typical tasks such as searching and
sorting

The whole framwork is generic in terms of both interfaces and classes, and the algorithms are
defined as generic methods. The description of this framework is the goal of the following
chapter. The first task is of course to get an overview of the content and in related to thatt
how the various classes can be used. Moreover, it is necessary to have a general knowledge
of how each class is implemented and working as it is a prerequisite for choosing the right
class for the right task.

9.1 OVERVIEW OF THE COLLECTION CLASSES


There are many interfaces and abstract classes, which together define the characteristics of
the collection classes, and I will mention below the main. Basic the framework is a hierarchy,
but there are individual classes which are outside the hierarchy. The main are abstract classes
and interfaces where I actually already have used some of them:

-- Iterable is an interface that defines that a class implements the iterator pattern, and
you can itererates the container’s objects with a for each statement.

Download free eBooks at bookboon.com


131
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection classes

-- Collection is a basic interface as the most of all collection classes in the hierarchy
implements. It’s rare that you directly refer to this interface, but it can be used if
you write very general methods, and some of methods in the class Collections have
parameters whose type is this interface.
-- List is an interface that defines containers that have a sequence of objects, where
each object is identified by an index. A List can not have holes, but it may contain
the same objects more than once. An ArrayList is an example of a List.
-- Set, SortedSet, NavigableSet, Queue and Deque are all interfaces for containers, not
allowing the same element to exists several times. A SortedSet arranges the elements
in sorted order, while a NavigableSet offers search options. Queue is an interface
where you can access the oldest element and the class Buffer is actually a Queue. We
call such a data structure for a FIFO structure for Firts In First Out. In contrast,
a Deque represent a data structure where you always have access to the newest
element, and you’re talking about a LIFO data structure for Last In First Out. A
stack is an example of a Deque.
-- Map, SortedMap, NavigableMap are base classes for containers which stores key /
value pairs. In a SortedMap the keys are stored in sorted order. A NavigableMap is
a Map, which offer special search options. These three classes are not part of the
same hierarchy as the other types of collection classes.
-- Iterator and ListIterator are interfaces for iterators, and the difference is that the last
interface defines the methods of traversing a collection in both directions.

The relationship between these types are as shown below:

Download free eBooks at bookboon.com


132
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection classes

I will not describe the individual types and the methods that they defines, but I will instead
refer to the Java documentation, but it is all types that you must know and including their
main characteristics.

The main konkete classes are as follows:

-- ArrayList. It is a class I have used many times and can short be characterized as
a dynamic array. The class implements the interface List. It is definitely the most
frequently used of the collection classes.
-- LinkedList. It is also a List, but is implemented in a different way than ArrayList
and is an example of a double-linked list. In addition the class implements both
List, Queue and Deque.
-- HashSet. It is a Set and is implemented by hashing (explained below), and its
primary quality is, that it is highly effective in terms of insertion and references
to the elements.
-- TreeSet. It is also a set, but is implemented in a completely different way by using
a red-black tree. Unlike a HashSet a TreeSet guarantees that the elements are sorted.
-- HashMap. It is a map, which is a data structure comprising of key/value pairs. It
implements the data structure using hashing.

AXA Global
Graduate Program
Find out more and apply

Download free eBooks at bookboon.com


Click on the ad to read more
133
JAVA4:
JAVA
JAVA 4:JAVA’S
4: JAVA’STYPE
JAVA’S TYPESYSTEM
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
ANDCOLLECTION CLASSES
COLLECTIONCLASSES
CLASSES ColleCtIon Classes
ColleCtIonclasses
Collection Classes

TreeMap. ItIt isis aa SortedMap,


--- TreeMap. SortedMap, and and in
in contrast
contrast toto aa HashMap
HashMap does does itit guarantee
guarantee that
that
the elements
the elements are are sorted
sorted byby keys.
keys. The
The data
data structure
structure isis implemented
implemented by by using
using aa
red-black tree.
red-black tree.
--- PriorityQueue.
PriorityQueue. ItIt isis aa data
data structure
structure that
that corresponds
corresponds to to aa Queue,
Queue, but but where
where one
one
can insert
can insert elements
elements after
after aa priority.
priority. The
The data
data structure
structure isis implemented
implemented usingusing aa heap
heap
(see below).
(see below).

In the
In the following
following II will
will deal
deal with
with these
these 77 data
data structures,
structures, focusing
focusing on
on their
their main
main features
features and
and
show examples
show examples of of how
how they
they are
are used.
used. II also
also roughly
roughly outlines
outlines how
how they
they are
are implemented,
implemented, as as
isis necessary
necessary inin order
order toto use
use these
these classes
classes effectively.
effectively.

9.2
9.2 ARRAYLIST
ARRAYLIST
An ArrayList
An ArrayList isis as
as mentioned
mentioned above,
above, aa dynamical
dynamical array,
array, that
that automatically
automatically grows
grows with
with the
the
number of
number of elements
elements andand you
you should
should have
have the
the following
following picture
picture of
of an
an ArrayList:
ArrayList:

where
where there
there are
are seven
seven elements
elements in
in the
the list.
list. When
When you you create
create anan ArrayList
ArrayList the
the internal
internal array
array
isis empty,
empty, but
but when
when you
you add
add an
an item
item to to the
the list,
list, there
there isis allocated
allocated room
room for
for 10
10 elements
elements
(the
(the number 10 actually depends on the implementation). The arrow indicates where the
number 10 actually depends on the implementation). The arrow indicates where the
next element is to be inserted, and the figure above illustrates such an ArrayList
next element is to be inserted, and the figure above illustrates such an ArrayList after that after that
the
the following
following statements
statements are
are performed:
performed:

ArrayList<Integer>
ArrayList<Integer> list
list =
= new
new ArrayList<>();
ArrayList<>();
list.add(11);
list.add(11);
list.add(5);
list.add(5);
list.add(17);
list.add(17);
list.add(3);
list.add(3);
list.add(7);
list.add(7);
list.add(23);
list.add(23);
list.add(19);
list.add(19);

IfIf you
you now
now further
further performs
performs the
the following
following statements:
statements:

list.add(0, 2);
list.add(0, 2);
list.add(5,
list.add(5, 29);
29);
list.add(13);
list.add(13);

Download free eBooks at bookboon.com


134
134
134
JAVA4:4:JAVA’S
JAVA JAVA’STYPE
TYPESYSTEM
SYSTEM
ANDCOLLECTION
AND COLLECTIONCLASSES
CLASSES ColleCtIonclasses
Collection Classes

thepicture
the pictureis:is:

Youshould
You shouldnote
notethat
thatyou
youcan
canuse
useadd()
add()with
withan
anindex
indexand
andthen
thenall
allelements
elementstotothe
theright
right
ofofthe
theindex
indexmost
mostbebemoved
movedtotomake
makeroom
roomforforthe
thenew
newelement.
element.YouYoushould
shouldalso
alsonote
note
thatafter
that afterthese
thesethree
threestatements,
statements,the
theentire
entirecapacity
capacityisisused
usedup,
up,and
andthethequestion
questionisiswhat
what
happensififyou
happens youadd
addanother
anotherelement
element

list.add(31);

AsAsmentioned
mentionedpreviously,
previously,the
theidea
ideaofofan
anArrayList
ArrayListisisthat
thatititautomatically
automaticallyexpands.
expands.When
When
thishappens
this happensthetheclass
classuses
usesananalgorithm,
algorithm,that
thatmultiply
multiplythe thecapacity
capacityby
byaaconstant
constant(often
(often
ititisis2),
2),but
butininmy
mypresent
presentimplementation,
implementation,ititisis1½.
1½.Therefore,
Therefore,the
thecapacity
capacityafter
afteradding
adding
anotherelement
another elementisis15:
15:

Thenext
The nexttime
timethe thearray
arrayisisextended,
extended,ititwill
willbebetotothe
thecapacity
capacity22,22,then
then33,
33,then
then49,
49,then
then7373
andsosoon.
and on.The
Theidea
ideaisisthat
thatininmost
mostcases
casesthe
theaddition
additionofofan
anelement
elementisisextremely
extremelyeffective,
effective,
andonly
and onlyininaafewfewcases
casesininwhich
whichthe
thearray
arrayisistotobe
beextended,
extended,there
thereisisfor
foraalong
longtask.
task.As
As
thearray
the arrayexpands
expandswithwithincreasing
increasingcapacity,
capacity,ititbecomes
becomesrarer
rarerthat
thatititmust
mustbebeexpanded,
expanded,and and
theresult
the resultofofall
allthis
thisisisthat
thatononaverage,
average,ititisisvery
veryeffective
effectivetotoadd
addelements
elementstotoan anArrayList.
ArrayList.

Asaaprogrammer
As programmeryou youshould
shouldnot
notthink
thinksosomuch
muchofofit,it,because
becauseititisissomething
somethingthat
thathappens
happens
internally,but
internally, butyou
youshould
shouldknow
knowthat
thatthe
themethods
methods

--- add(),that
add(), thatadd
addananelement
elementtotothe
theend
endofofthe
thelist
list
--- get(),that
get(), thatreturns
returnsthe
theelement
elementatataaparticular
particularindex
index

arehighly
are highlyeffective,
effective,while
whilemethods
methodslike
like

--- add(),that
add(), thatadds
addsan
anelement
elementatataaparticular
particularindex
index
--- remove(),that
remove(), thatremoves
removesan
anelement
element

areless
are lesseffective
effectiveasasthey
theypossibly
possiblymust
mustmove
movemany
manyofofthe
theelements
elementsininthe
thelist
list(a(alist
listmust
must
nothave
not haveholes).
holes).

Download free eBooks at bookboon.com


135
135
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA4:
4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND COLLECTION CLASSES ColleCtIon Classes
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Collection
ColleCtIonclasses
Classes

In general,
In general, an ArrayList
ArrayList is highly effective
effective and that
that it periodically must
must be expanded
expanded to
In general, anan ArrayList isis highly
highly effective and
and that itit periodically
periodically must be
be expanded to to
increase
increase the capacity is not something you have to think about. As an example is shown a list
increasethe
thecapacity
capacityisisnot
notsomething
somethingyou youhave
haveto
tothink
thinkabout.
about.As
Asan
anexample
exampleisisshown
shownaalist
list
initialized
initialized with random numbers and then the method determines the sum of the numbers:
initializedwith
withrandom
randomnumbers
numbersand andthen
thenthe
themethod
methoddetermines
determinesthethesum
sumof
ofthe
thenumbers:
numbers:
private static void test01(List<Integer> list, int n)
private static void test01(List<Integer> list, int n)
{
{
long t1 = Calendar.getInstance().getTimeInMillis();
long t1 = Calendar.getInstance().getTimeInMillis();
while (n-- > 0) list.add(rand.nextInt());
while (n-- > 0) list.add(rand.nextInt());
long t2 = Calendar.getInstance().getTimeInMillis();
long t2 = Calendar.getInstance().getTimeInMillis();
long s = 0;
long s = 0;
long t3 = Calendar.getInstance().getTimeInMillis();
long t3 = Calendar.getInstance().getTimeInMillis();
for (Integer t : list) s += t;
for (Integer t : list) s += t;
long t4 = Calendar.getInstance().getTimeInMillis();
long t4 = Calendar.getInstance().getTimeInMillis();
System.out.println(t2 – t1);
System.out.println(t2 – t1);
System.out.println(t4 – t3);
System.out.println(t4 – t3);
}
}

IfIf II performs
performs the
the method
method on
on my
my machine
machine with
with the
the following
following statement
statement
If I performs the method on my machine with the following statement
test01(new ArrayList<Integer>(), 1000000);
test01(new ArrayList<Integer>(), 1000000);

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

Download free eBooks at bookboon.com


Click on the ad to read more
136
136
136
JAVA
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA4:
4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
AND
AND COLLECTION
COLLECTION
COLLECTION CLASSES
CLASSES
CLASSES ColleCtIon
ColleCtIon
Collection Classes
Classes
AND COLLECTION CLASSES ColleCtIonclasses
Classes

the
the
the method
method
themethod must
must
methodmust be
be
mustbe added
addedaaaamillion
added
beadded million
million elements
elements
millionelements to
elementstoto the
the
tothe list,
list,
thelist, and
and
list,and on
on
andon my
my
onmy machine
machine
mymachine the
the
machinethe result
result
theresult was:
was:
resultwas:
was:

31
31
31
66
6

This
This means
This
This means that
means
means that ititit
that
that it has
has taken
has
has taken 31
taken
taken 31 milliseconds
31
31 milliseconds of
milliseconds
milliseconds of initializing
of
of initializing the
initializing
initializing the list
the
the list and
list
list and 666
and
and 6 milliseconds
milliseconds to
milliseconds
milliseconds to
to
to
determine
determine
determine the
the
the sum.
sum.
sum. If
If
If I
II change
change
change the
the
the initialization
initialization
initialization
determine the sum. If I change the initialization statement to statement
statement
statement to
to
to

while
while (n--
(n-- >> 0)
0) list.add(0,
while (n-- rand.nextInt());
> 0) list.add(0,
list.add(0, rand.nextInt());
rand.nextInt());

and
and performs
and
and performs the
performs
performs the method
the
the method again,
method
method again, IIII get
again,
again, get the
get
get the result:
the
the result:
result:
result:

45876
45876
45876
66
6

and
and it will say that it has now taken over a¾ minute to insert the numbers in the list, and
and itit
and it will
will say
will say that
say that itit
that it has
has now
has now taken
now taken over
taken over aaa ¾
over ¾ minute
¾ minute to
minute to insert
to insert the
insert the numbers
the numbers in
numbers in the
in the list,
the list, and
list, and
and
it’s
it’s
it’s quite
quite a
a difference.
difference. The
The reason
reason is
is that
that the
the elements
elements this
this time
time are
are inserted
inserted at
at the
the beginning
beginning
it’s quite
quite aa difference.
difference. TheThe reason
reason is is that
that the
the elements
elements thisthis time
time are
are inserted
inserted at
at the
the beginning
beginning
of
of the list and all other elements in the list must therefore be moved one place to the right.
of the list and all other elements in the list must therefore be moved one place to the
of the
the list
list and
and all
all other
other elements
elements in
in the
the list
list must
must therefore
therefore be
be moved
moved one
one place
place to
to the right.
the right.
right.
The
The example illustrates the great the difference in terms of efficiency depending on how the
The example illustrates the great the difference in terms of efficiency depending on how the
The example
example illustrates
illustrates the
the great
great the
the difference
difference in
in terms
terms of
of efficiency
efficiency depending
depending on
on how
how the
the
elements
elements
elements are
are
are inserted
inserted
inserted and
and
and ititit is
is
is aaa difference
difference
difference that
that
that you
you
you in
in
in practice
practice
practice must
must
must be
be
be aware
aware
aware of.
of.
of.
elements are inserted and it is a difference that you in practice must be aware of.

You
You can also create an ArrayList from another collection, where I here use the class Arrays,
You can
You can also
can also create
also create an
create an ArrayList
an ArrayList from
ArrayList from another
from another collection,
another collection, where
collection, where III here
where here use
here use the
use the class
the class Arrays,
class Arrays,
Arrays,
which
which
which has
has
has aaa method
method
method that
that
that creates
creates
creates aaa List:
List:
List:
which has a method that creates a List:

ArrayList<Integer>
ArrayList<Integer> list
list == new
new ArrayList<>(Arrays.asList(11, 5,
5, 17, 3,
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(11,
ArrayList<>(Arrays.asList(11, 5, 17, 3, 7));
17, 3, 7));
7));

In
In this
this
In this
In case,
case,
this case, the
the
case, the list
list
the list capacity
capacity
list capacity isis
capacity is the
the
is the number
number
the number of
of
number of arguments
arguments
of arguments that
that
arguments that have
have
that have been
been
have been transferred
transferred
been transferred and
and
transferred and
and
hence
hence
hence 55
hence 5 in
5 inin this
this
in this case.
case.
this case.
case.

As
As another
another
As another
As example,
example,
another example, regarding
regarding
example, regarding lists
lists
regarding lists are
are
lists are shown
shown aaaa method
shown
are shown method
method that
that
method that prints
prints aaaa collection:
prints
that prints collection:
collection:
collection:

private
private static
private static void
static void print(Collection<?>
void print(Collection<?> c)
print(Collection<?> c)
c)
{{
{
for
for (Object
for (Object ee
(Object e ::
: c)
c) System.out.print(e
c) System.out.print(e ++
System.out.print(e + ""
" ");
");
");
System.out.println();
System.out.println();
System.out.println();
}}
}

The
The
The method
method
The method
method is isis trivial,
trivial,
is trivial, but
but
trivial, but you
you
but you should
should
you should note
note
should note two
two
note two things.
things.
two things. The
The
things. The parameter
parameter
The parameter
parameter isisis
is aaaa Collection
Collection
Collection
Collection
parameterized
parameterized
parameterized
parameterized with with
with
with anan
an unbound
unbound
an unbound wildcard,
wildcard,
unbound wildcard, and
and
wildcard, and you
you
and you can
can
you can then
then
can then transfer
transfer
then transfer any
any
transfer any Collection
Collection
any Collection
Collection as as
as aaaa
as
parameter.
parameter.
parameter.
parameter. InIn
In addition,
addition,
In addition, please
please
addition, please note
note
please note that
that
note that the
the
that the Collection
Collection
the Collection inherits
inherits
Collection inherits Iterable
Iterable
inherits Iterable and
and
Iterable and therefore
therefore
and therefore one
one
therefore one
one
can
can
can iterate
iterate
can iterate over
over
iterate over a
a collection
collection
over aa collection with
with
collection with for
for
with for each.
each.
for each.
each.

Download free eBooks at bookboon.com


137
137
137
137
JAVA 4:
JAVA 4: JAVA’S TYPE
TYPE SYSTEM
JAVA 4: JAVA’S
JAVA’S TYPE SYSTEM
SYSTEM
AND COLLECTION
AND COLLECTION CLASSES
CLASSES ColleCtIon classes
Collection Classes
AND COLLECTION CLASSES ColleCtIon Classes

As
As aaa final
As final note
final note
note toto the
to the class
the class ArrayList
class ArrayList please
ArrayList please note
please note that
that itit
note that implements
it implements
implements the the interface
the interface List
interface List and
List and
and
thus
thus Collection
Collection and
and Iterable.
Iterable. Moreover
Moreover the
the class
class also
also implements
implements
thus Collection and Iterable. Moreover the class also implements three other interfaces: three
three other
other interfaces:
interfaces:
Serializable,
Serializable, Cloneable
Serializable, Cloneable
Cloneable and and RandomAccess.
and RandomAccess.
RandomAccess. The The first
The first interface
interface isis
first interface discussed
is discussed ealier,
discussed ealier, Cloneable
Cloneable III
ealier, Cloneable
also
also mentioned
also mentioned earlier,
mentioned earlier, and
earlier, and the
and the last
the last interface
interface isis
last interface is aaa simple
simple interface
simple interface with
interface with no
with no methods
no methods (such
methods (such
(such
an
an interface
an interface is called
interface isis called a marker
called aa marker interface).
marker interface). It tells
interface). ItIt tells the
tells the runtime
the runtime system
runtime system that
system that the
that the elements
the elements
elements inin an
in an
an
ArrayList
ArrayList can
can be
be referenced
referenced by
by an
an
ArrayList can be referenced by an index. index.
index.

9.3
9.3
9.3 LINKEDLIST
LINKEDLIST
LINKEDLIST
It’s
It’s also
also aaa list,
It’s also list, and
list, and the
and the class
the class implements
class implements
implements in in the
in the same
the same way
same way as
way as an
as an ArrayList
an ArrayList
ArrayList the the interface
the interface List.
interface List. In
List. In
In
addition,
addition, it
it implements
implements the
the interfaces
interfaces Deque
Deque and
and Queue.
Queue. Finally,
Finally, it
it
addition, it implements the interfaces Deque and Queue. Finally, it implements Serializable implements
implements Serializable
Serializable
and
and Cloneable
and Cloneable
Cloneable but but not
but not RandomAccess.
not RandomAccess.
RandomAccess. The The class
The class also
class also has
also has other
has other methods
other methods
methods than than an
than an ArrayList,
an ArrayList,
ArrayList,
but
but what matters is that it is implemented in a whole different way,
but what matters is that it is implemented in a whole different way, as a double linked list.
what matters is that it is implemented in a whole different way, as
as aa double
double linked
linked list.
list.

IfIf you
If you creates
creates aaa LinkedList
you creates LinkedList
LinkedList

LinkedList<Integer>
LinkedList<Integer> list
list =
= new
new LinkedList();
LinkedList();

you have
you have
you an
have an empty
an empty list,
empty list, which
list, which you
which you should
you should think
should think about
think about in
about in the
in the following
the following way:
following way:
way:

that
that isis
that two
is two pointers
two pointers pointing
pointers pointing respectively
pointing respectively to
respectively to start
to start and
start and end
and end
end ofof the
of the list.
the list. That
list. That
That the the list
list isis
the list empty
is empty
empty
means
means that the two pointers both are null. The class has an add()
means that the two pointers both are null. The class has an add() method that works the
that the two pointers both are null. The class has an add() method
method that
that works
works the
the
same
same way as in an ArrayList and adds an element to the end of the list. If you perform the
same way
way as
as in
in an
an ArrayList
ArrayList and
and adds
adds an
an element
element to
to the
the end
end of
of the
the list.
list. If
If you
you perform
perform the
the
following
following statements
statements
following statements

list.add(11);
list.add(11);
list.add(13);
list.add(13);

the
the picture of the list is as below:
the picture
picture of
of the
the list
list is
is as
as below:
below:

Download free eBooks at bookboon.com


138
138
138
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Collection
ColleCtIon classes
Classes

A
A LinkedList
LinkedList consists
consists of
of so-called
so-called nodes,
nodes, where
where aa node
node includes
includes aa data
data item
item and
and aa pointer
pointer to
to
the
the previous
previous node,
node, and
and aa pointer
pointer toto the
the next
next node
node inin the
the list.
list. The
The first
first node
node (data
(data element
element
11)
11) has no predecessor, and its pointer to the previous node is null, and, similarly, the
has no predecessor, and its pointer to the previous node is null, and, similarly, the
pointer to the next item in the node with the data element 13 is also null.
pointer to the next item in the node with the data element 13 is also null. In turn, node In turn, node
11
11 points
points forward
forward on
on node
node 13,
13, while
while node
node 13
13 points
points back
back toto node
node 11.
11.

Compared
Compared to
to an
an ArrayList
ArrayList aa LinkedList
LinkedList has
has several
several methods
methods to
to add
add items
items to
to the
the list:
list:

list.addFirst(2);
list.addLast(53);
list.add(3, 19);

Here are addFirst() and addLast() are just special names for add() with index 0 and add()
Here are addFirst() and addLast() are just special names for add() with index 0 and add()
with no index. If the above statements are performed, the result is:
with no index. If the above statements are performed, the result is:

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management [email protected] Follow us on IE MIM Experience

Download free eBooks at bookboon.com


Click on the ad to read more
139
139
JAVA
JAVA4:
4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
AND COLLECTIONCLASSES
CLASSES Collection
ColleCtIonclasses
Classes
AND COLLECTION CLASSES ColleCtIon Classes

The
The idea
idea with
with aa LinkedList
LinkedList isis that,
that, when
when compared
compared with
with anan ArrayList
ArrayList itit isis simple
simple to
to insert
insert
The idea with a LinkedList is that, when compared with an ArrayList it is simple to insert
an
an element
element and
and delete
delete an
an element
element in in the
the middle
middle of
of the
the list.
list. If,
If, for
for example
example you you performs
performs
an element and delete an element in the middle of the list. If, for example you performs
the statement
the statement
the statement
list.add(3, 17);
list.add(3, 17);

element 17
element 17 has to
to be inserted
inserted between 13
13 and 19:
19:
element 17 has
has to be
be inserted between
between 13 and
and 19:

This means
This means to create
create a new node,
node, and then
then change the
the 4 pointers, but
but you should
should not in
in
This means to
to create aa new
new node, and
and then change
change the 44 pointers,
pointers, but you
you should not
not in
the same
the same way as
as with anan ArrayList move
move all elements
elements to the
the right of
of the place
place where the
the
the same way
way as with
with an ArrayList
ArrayList move all
all elements to
to the right
right of the
the place where
where the
new element
new element should be
be inserted.
new element should
should be inserted.
inserted.

IfIf you assume


If you
assume that the
you assume that
the element 17
that the element
17 is inserted and
element 17 isis inserted
and you performs
inserted and you
performs the statement
you performs the
statement
the statement
list.remove(3);
list.remove(3);
is the result
is the result
is the result

This means that there are changed two pointers, and there is thus no longer references to
This means that there are changed two pointers, and there is thus no longer references to
the item 17, which are then removed by the garbage collector. Again, the benefit is the same
the item
This means 17,that
which areare
there then removed
changed by pointers,
two the garbage
andcollector.
there is Again,
thus nothe benefit
longer is the same
references to
that deletion requires few operations. Both insertion and deletion of elements is simple,
thatitem
the deletion requires
17, which few operations.
are then removed by Both insertion
the garbage and deletion
collector. of elements
Again, the benefit is isthesimple,
same
but requires special implementations of both inserting or deleting of elements in the ends
but requires
that deletion special
requiresimplementations
few operations. ofBoth
bothinsertion
insertingand
or deleting
deletion of
of elements
elementsinis the ends
simple,
of the list.
of the
but list. special implementations of both inserting or deleting of elements in the ends
requires
of the list.

Download free eBooks at bookboon.com


140
140
140
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection classes

Another property of a LinkedList is, that it is not in the same way as an ArrayList allocates
available capacity and periodically needs to expand, but on the other hand, each node uses
two additional pointers to neighbor elements, which also fills, and it in reality means that
a LinkedList not use less memory space than an ArrayList – and actually a bit more. With
regard og inserting and deleting elements in the middle of the list you should be aware
that although the operations are effective similar to that they simply consists of moving a
few pointers, but you should be aware that the access to the list is only possible through
the two pointers start and end, and there is therefore in principle necessary first to find
the place where to insert or delete an element – the class does not implement the interface
RandomAccess.

The most important characteristics of a LinkedList is that it is very effective to insert and
delete items in the beginning of the list, and the like at the end of the list (as an ArrayList).
These are the characteristics which are required by the implementation of a queue and a stack.

A queue is a data structure where you primary can add an item and removing an item but
such that the element that is removed, always is the oldest element – it’s the element been
the longest in the queue. Typically, you have the following picture of a queue

which adds elements where tail is pointing and remove the element where head is pointing.
Since a LinkedList just performs well when inserting elements at the end of the list and to
remove elements at the start of the list, it is suitable for implementing a queue, and that is
expressed that the class implements the interface Queue. This interface defines 6 methods,
that apart from the exceptions they can raise works in pairs like:

-- offer() and add(), that add an element to the queue


-- poll() and remove() that removes an element from the queue
-- peek() and element(), that returns the oldest element without removing it

Below is a method that creates a queue and inserts 6 elements in the queue (similar to
the figure above). Then the method prints the contents of the queue, and there after the
queue is empy:

Download free eBooks at bookboon.com


141
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Collection classes
AND COLLECTION CLASSES ColleCtIon Classes

private static void test02()


{
Queue<Integer> q = new LinkedList();
q.offer(2);
q.offer(3);
q.offer(5);
q.offer(7);
q.offer(11);
q.offer(13);
print(q);
while (q.size() > 0) System.out.print(q.poll() + " ");
System.out.println();
}

Download free eBooks at bookboon.com


Click on the ad to read more
142
142
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Collection
ColleCtIonclasses
Classes

AAstack
stackisislook
looklikes
likesaaqueue,
queue,and andititisisagain
againaadata
datastructure,
structure,where
whereyouyoucan
canadd
addand andremove
remove
elements,
elements,but butthis
thistime
timeititisisthe
theelement
elementthat thatwas
waslast
lastadded
addedtotothe
thestack,
stack,that
thatisisisisremoved.
removed.
AAstack
stackcancanbe
beillustrated
illustratedasasshown
shownhere:here:

wherethere
where thereare
are66elements
elementsom omthe thestack.
stack.The
Thearrow
arrowindicates
indicatesthe
theplace
placewhere
wherethethenext
next
elementshould
element shouldbe beadded.
added.The
Theimplementation
implementationofofaastack
stackmust
mustbebedone
doneusing
usingaadata
datastructure
structure
thatisiseffective
that effectiveininterms
termsofofinsertion
insertionofofananelement
elementininthe thestack
stackand
andthen
thentotoremove
removethe the
elementagain.
element again.These
Theserequirements
requirementsmeets
meetsboth
bothan anArrayList
ArrayListand andaaLinkedList.
LinkedList.InInthe
thecase
caseofof
aastack
stackthethetwo
twooperations
operationsforforinserting
insertingelements
elementsininaastack
stackandandremove
removeelements
elementsfrom
fromthethe
topofofaastack
top stackisisrespectively
respectivelycalled
calledpush()
push()and
andpop().
pop().AAdeque
dequeisisaaqueue,
queue,where
whereyou youcancan
insertand
insert andremove
removeelements
elementsbothbothatatthe
thebeginning
beginningandandend endofofthe
thequeue,
queue,andandwhen
whenthe the
classLinkedList
class LinkedListimplements
implementsthe theinterface
interfaceDeque,
Deque,ititisisininprinciple
principleaastack.
stack.The
Thefollowing
following
methodshows
method showshowhowyouyouininJava
Javacan
candefine
defineand
anduse
useaastack:
stack:

private static void test03()


{
Deque<Integer> s = new LinkedList();
s.push(2);
s.push(3);
s.push(5);
s.push(7);
s.push(11);
s.push(13);
print(s);
while (s.size() > 0) System.out.print(s.pop() + " ");
System.out.println();
}

There is also a second collection class called ArrayDeque which implements a deque by
There is also a second collection class called ArrayDeque which implements a deque by
means of an ArrayList. It is with respect to a stack of slightly more effective.
means of an ArrayList. It is with respect to a stack of slightly more effective.

Download free eBooks at bookboon.com


143
143
JAVA
JAVA4:
4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Collection
ColleCtIonclasses
Classes

EXERCISE
EXERCISE 10
10
Write
Write ee program,
program, thatthat you
you can
can call
call ListProgram.
ListProgram. The
The program
program should
should do do the
the same
same asas the
the
method
method test01()
test01() above,
above, that
that isis add
add 1000000
1000000 random
random integers
integers to
to aa list,
list, and
and then
then iterartes
iterartes
the
the list
list and
and determines
determines thethe sum
sum of of the
the numbers.
numbers. The
The program
program must
must for for each
each of
of the
the two
two
operations prints how long this will take, but this time the list must be a LinkedList<Integer>.
operations prints how long this will take, but this time the list must be a LinkedList<Integer>.
Compare
Compare the the result
result with
with the
the result
result afaf executing
executing the
the method
method test01().
test01().

PROBLEM
PROBLEM 33
You
You should
should write
write aa program
program called
called StackProgram,
StackProgram, that
that can
can be
be used
used to
to test
test aa Deque,
Deque, when
when
the
the type
type isis used
used as
as aa stack.
stack.

Add
Add aa simpel
simpel generic
generic print
print method
method

private static <T> void print(T[] arr)


{
}

when the
when the methed
methed must
must print
print the
the array
array arr
arr with
with all
all elements
elements on
on the
the same
same line
line separated
separated by
by
aa space.
space.

ItIt isis possible


possible to
to sort
sort an
an array
array using
using two
two stacks,
stacks, and
and the
the following
following algorithm
algorithm can
can be
be used:
used:

for each element t i in the array repeat


{
as long t i less than the top of the left stack do
{
pop the left stack and push the element on the right stack
}
as long t is greater than the top of the right stack do
{
pop the right stack and push the element on the left stack
}
push t on the left stack
}
as long the left stack is not empty do
{
pop the left stack and push the element on the right stack
}
loop over the array from start to end
{
pop the right stack and insert the element in the array
}

Download free eBooks at bookboon.com


144
144
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection classes

Write a generic method stackSort(T[] arr) that implements the above algorithm and sorts
an array.

Write a method test1(), that creates an array of the type Integer with 100 random numbers,
such that every number is greater than 9 and less than 100. The method should print the
array, sort it with the method stackSort() and print the array again.

Write a method test(int n), that creates an Integer array with n random elementens. The
method should sort the array with stackSort() and print how many milliseconds the sorting
has taken. What happens if n is 100, 1000, 10000, 100000?

9.4 HASHSET
The interface Set defines a mathematical set and including the operations that you would
typically expect to perform on sets. In chapter 6 you have written a class that could represent
a set using an ArrayList, but I also noticed that the implementation of the set was not
especially effective. Java, however, has a class HashSet which also represents a set, and is in
turn effective. Consider the following method:

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

Download free eBooks at bookboon.com


Click on the ad to read more
145
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
JAVA COLLECTION CLASSES
4: JAVA’S TYPE SYSTEM ColleCtIon Classes
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Collection
ColleCtIonclasses
Classes
AND COLLECTION CLASSES ColleCtIon Classes

private static void test04()


private static void test04()
private static void test04()
{
{
{ Set<Integer> A = new HashSet();
Set<Integer> A = new HashSet();
Set<Integer> BA = new HashSet();
Set<Integer> B = new HashSet();
Set<Integer>
for (int i = B0;= inew HashSet();
< 10; ++i)
for (int i = 0; i < 10; ++i)
for (int i = 0; i < 10; ++i)
{
{
{ A.add(rand.nextInt(10));
A.add(rand.nextInt(10));
A.add(rand.nextInt(10));
B.add(rand.nextInt(10));
B.add(rand.nextInt(10));
} B.add(rand.nextInt(10));
}
}
Set<Integer> C = new HashSet(A);
Set<Integer> C = new HashSet(A);
Set<Integer>
C.addAll(B); C = new HashSet(A);
C.addAll(B);
C.addAll(B); D = new HashSet(A);
Set<Integer>
Set<Integer> D = new HashSet(A);
Set<Integer> D = new HashSet(A);
D.retainAll(B);
D.retainAll(B);
D.retainAll(B);
Set<Integer> E = new HashSet(A);
Set<Integer> E = new HashSet(A);
Set<Integer> E = new HashSet(A);
E.removeAll(B);
E.removeAll(B);
E.removeAll(B);
print(A);
print(A);
print(A);
print(B);
print(B);
print(B);
print(C);
print(C);
print(C);
print(D);
print(D);
print(D);
print(E);
print(E);
} print(E);
}
}

This method creates two sets A and B and initializes them with digits. Next are determined
Thismethod
This methodcreates
createstwo
twosets
setsAAand
and Band
andinitializes
initializesthem
themwithwithdigits.
digits.Next
Nextare
aredetermined
determined
This methodthe
respectively creates two
union, sets A andBand
intersection B and
set initializes
difference.them
If thewith digits.
method is Next are determined
performed the result
respectivelythe
respectively theunion,
union,intersection
intersectionand
andset
setdifference.
difference.IfIfthe
themethod
methodisisperformed
performedthe
theresult
result
respectively
could be: the union, intersection and set difference. If the method is performed the result
couldbe:
could be:
could be:
0 1 5 6 8
0 1 5 6 8
0 1 5
2 6
4 8
7 8 9
0 1 2 4 7 8 9
0 1 2 4 7
5 8
6 9 8 9
7
0 1 2 4 5 6 7 8 9
0 1 2
8 4 5 6 7 8 9
0 1 8
0
5 1
6 8
5 6
5 6

The
Theset
setAAhas
has55elements,
elements,andandthethesetsetBBhas
has77elements.
elements.You Youshould
shouldtotonotenotethat
thatthe
thereason
reason
The set A has 5 elements, and the set B has 7 elements. You should to note that the reason
The
why set
whythe A has
thenumber 5 elements,
numberofofelements and
elementsare the set B
aredifferent has
differentand 7 elements.
andthere
thereare You
arenot should
not10 to
10elements note that
elementsinineach the
eachsetreason
set due
due
why the number of elements are different and there are not 10 elements in each set due
why
to, the
to,that
thatthenumber
thesame of elements
sameelement
elementcan are
canonly different
onlyoccur and
occuronce.
once.You there are
Youshould not
shouldalso10 elements
alsonote
notethat in each
thatititlooks set
lookslike due
likethe
the
to, that the same element can only occur once. You should also note that it looks like the
to, that the
elements
elements are same element
areordered,
ordered,but can
butitit only
isisonly occur
onlyapparent, once.
apparent, and
and You should
ininconnectionalso with
connection note
withathat it looks
aHashSet
HashSet youlike
you the
must
must
elements are ordered, but it is only apparent, and in connection with a HashSet you must
elements
not
notassume
assumeareany
ordered,
any but it isofofonly
arrangement
arrangement theapparent,
the elements.and
elements. Youin
You connection
finally
finally shouldwith
should notes
notesa the
HashSet
thenames you
names ofofmust
the
the
not assume any arrangement of the elements. You finally should notes the names of the
not assume
methods,
methods,where any arrangement
whereaddAll()
addAll()isisunion,of the elements.
union,retainlAll() You finally
retainlAll()isisintersection
intersectionand should notes
andremoveAll() the
removeAll()isisset names of the
setdifference.
difference.
methods, where addAll() is union, retainlAll() is intersection and removeAll() is set difference.
methods, where addAll() is union, retainlAll() is intersection and removeAll() is set difference.
Consider
Considerasasanother
anotherexample,
example,the
thefollowing
followingmethod:
method:
Consider as another example, the following method:
Consider as another example, the following method:
private static void test05(int n)
private static void test05(int n)
private static void test05(int n)
{
{
{ Set<Integer> A = new HashSet();
Set<Integer> A = new HashSet();
Set<Integer> A = new HashSet();

Download free eBooks at bookboon.com


146
146
146
146
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Collection classes
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES ColleCtIon Classes
AND COLLECTION CLASSES ColleCtIon Classes

Set<Integer> B = new HashSet();


Set<Integer> B = new HashSet();
long t1 = Calendar.getInstance().getTimeInMillis();
long t1 = Calendar.getInstance().getTimeInMillis();
for (int i = 0; i < n; ++i)
for (int i = 0; i < n; ++i)
{
{
A.add(rand.nextInt(n));
A.add(rand.nextInt(n));
B.add(rand.nextInt(n));
B.add(rand.nextInt(n));
}
}
long t2 = Calendar.getInstance().getTimeInMillis();
long t2 = Calendar.getInstance().getTimeInMillis();
System.out.println(A.size() + " " + B.size() + " " + (t2 – t1));
System.out.println(A.size() + " " + B.size() + " " + (t2 – t1));
long t3 = Calendar.getInstance().getTimeInMillis();
long t3 = Calendar.getInstance().getTimeInMillis();
Set<Integer> C = new HashSet(A);
Set<Integer> C = new HashSet(A);
C.addAll(B);
C.addAll(B);
long t4 = Calendar.getInstance().getTimeInMillis();
long t4 = Calendar.getInstance().getTimeInMillis();
System.out.println(C.size() + " " + (t4 – t3));
System.out.println(C.size() + " " + (t4 – t3));
long t5 = Calendar.getInstance().getTimeInMillis();
long t5 = Calendar.getInstance().getTimeInMillis();
Set<Integer> D = new HashSet(A);
Set<Integer> D = new HashSet(A);
D.retainAll(B);
D.retainAll(B);
long t6 = Calendar.getInstance().getTimeInMillis();
long t6 = Calendar.getInstance().getTimeInMillis();
System.out.println(D.size() + " " + (t6 – t5));
System.out.println(D.size() + " " + (t6 – t5));
long t7 = Calendar.getInstance().getTimeInMillis();
long t7 = Calendar.getInstance().getTimeInMillis();
Set<Integer> E = new HashSet(A);
Set<Integer> E = new HashSet(A);
E.removeAll(B);
E.removeAll(B);
long t8 = Calendar.getInstance().getTimeInMillis();
long t8 = Calendar.getInstance().getTimeInMillis();
System.out.println(E.size() + " " + (t8 – t7));
System.out.println(E.size() + " " + (t8 – t7));
}
}

This
This method
Thismethod creates
methodcreates two
createstwo sets
setsofof
twosets random
ofrandom integers
randomintegers between
between00
integersbetween and
andn,n,
0and and
n,and then
andthen creates
thencreates the
createsthe
the
union,
union, intersection
union,intersection and
intersectionand set
andset difference.
setdifference. The
difference.The method
Themethod prints,
methodprints, how
prints,how long
howlong each
longeach operation
eachoperation took:
operationtook:
took:
Below
Below is the
Belowisisthe result
theresult of executing
resultofofexecuting
executingthe the method
themethod with
methodwith n = 10000000:
withnn==10000000:
10000000:

6321515 6321068 9696


6321515 6321068 9696
8646902 1365
8646902 1365
3995681 3630
3995681 3630
2325834 1184
2325834 1184

It has taken about 10 seconds


seconds toto try
try toto create the two sets with 10 million members,
ItIt has
has taken
taken about
about 10 10 seconds to try to create
create the
the two
two sets
sets with
with 1010 million
million members,
members,
and
andthethe result
theresult is sets
resultisissets at approximately
setsatatapproximately 6
approximately66millionmillion elements.
millionelements. Secondly,
elements.Secondly, it has
Secondly,itithas taken
hastaken about
takenabout
about
and
1½ seconds
1½seconds to perform
secondstotoperform
performthe the union,
theunion, about
union,about
about3½ 3½ seconds
3½seconds to form
secondstotoform
formthethe intersection
theintersection
intersectionandand finally
andfinally
finally

just about
justabout 1 second
about11second to form
secondtotoform
formthethe set
theset difference.
setdifference.
difference.TheThe conclusion
Theconclusion is that
conclusionisisthat a HashSet
HashSetisisaaavery
thataaHashSet is very
very
just
efficient data
efficientdata structure.
datastructure.
structure.
efficient

Download free eBooks at bookboon.com


147
147
147
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection classes

A HashSet is implemented by hashing, which is a technique in which an element in a


collection can be found by a calculation. Internal, the collection is an array of sufficient
size and the individual objects are placed in the array. When you add a new object, the
class calculates using an algorithm where in the array the object must be placed, and it is
placed there (if the place is not already used). Similarly, if you want to get a specific object
in the collection, then the class just calculate the object’s place and test whether it exists.
There is direct access to the individual objects without any search, and that is exactly what
makes the data structure extremely effective.

An Object has a method called hashCode(), which returns an int. When objects of a given
type can be stored in a HashSet, the object’s class must overrides the method hashCode()
with value semantic. It is a requirement that two objects that are equals() also must have
the same hashCode(), but it is also the only formal requirements. On the other hand, it is
the programmer’s responsibility to ensure that hashCode() is implemented in such a way that
the method returns values that are uniformly distributed. It should be particularly noted
that it is not a requirement that the two objects with the same hashCode() are equals().

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

Download free eBooks at bookboon.com


Click on the ad to read more
148
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection classes

9.5 TREESET
The class TreeSet is also a Set, and you can exactly do the same as you can with a HashSet,
and the difference is that a TreeSet arranges the elements in a specific order. The elements to
be added to a TreeSet must therefore be objects created on basis of a class that implements
the interface Comparabel. If so, it sounds reasonable to use a TreeSet, if you needs a Set,
but you should be aware that a TreeSet not have the same effectiveness as a HashSet, and if
you do not need that the elements are sorted, you should choose a HashSet. It’s clear that
it costs something when you have to insert elements and possible delete them again such
that elements must be sorted.

It is not such that a TreeSet is inefficient and if you needs a sorted set, you should definitely
not disregard a TreeSet. Internally a TreeSet does not consists of an array, but is instead a
data structure composed of nodes that are linked together in much the same way as in a
LinkedList. In a TreeSet elements are organized in a binary tree:

and the requirements are that each element may not have more than two direct sequels, and
there should be exactly one element that has no predecessors and is called the root of the
tree. Furthermore, it must be the case that if you stand in a particular node, then the left
child must be null or less than where you stand, and the right child must be null or greater.
The sum of all this is that if you stand in a certain node, then that node is root of a subtree
in which all elements of the left subtree is less than the root and all elements in the right
subtree is greater than the root. This is exactly what gives the tree and thereby also a TreeSet
its qualities. You can then search the tree after the same principle as for binary search, and
it is thus highly effective to ask whether an element is in a TreeSet, and iterating the data
structure’s elements such that the elements are visited in sorted order are equally effective.

Download free eBooks at bookboon.com


149
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Collection
ColleCtIonclasses
Classes

EXERCISE
EXERCISE11
11
Create
Createaaprogram,
program,that
thatyou
youcan
cancall
callTreeProgram.
TreeProgram.Add
Addthe
thefollowing
followingclass
classtotothe
theproject:
project:

package treeprogram;
public class Person implements Comparable<Person>
{
private String firstname;
private String lastname;

public Person(String firstname, String lastname)


{
this.firstname = firstname;
this.lastname = lastname;
}

public String getFirstname()


{
return firstname;
}

public String getLastname()


{
return lastname;
}

public String toString()


{
return firstname + " " + lastname;
}

public boolean equals(Object obj)


{
if (obj == null) return false;
if (getClass() == obj.getClass())
{
Person pers = (Person)obj;
return firstname.equals(pers.firstname) && lastname.equals(pers.lastname);
}
return false;
}

public int hashCode()


{
return firstname.hashCode() ^ lastname.hashCode();
}

Download free eBooks at bookboon.com


150
150
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA COLLECTION
AND 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES
CLASSES Collection
ColleCtIon classes
Classes
AND COLLECTION CLASSES ColleCtIon Classes

public int compareTo(Person pers)


public int compareTo(Person pers)
{
{
if (lastname.equals(pers.lastname)) return firstname.compareTo(pers.firstname);
if (lastname.equals(pers.lastname)) return firstname.compareTo(pers.firstname);
return lastname.compareTo(pers.lastname);
return lastname.compareTo(pers.lastname);
}
}
}
}

The class represents a person with a name, and there is nothing to explain, but you should
The class represents a person with a name, and there is nothing to explain, but you should
note, that the class implements equals(), such that two Person objects are equals, if they have
note, that the class implements equals(), such that two Person objects are equals, if they have
the same name. The class also implements hashCode(), and the method use a XOR operation,
the same name. The class also implements hashCode(), and the method use a XOR operation,
and although I have not yet explained what it is, it is enough to know that hashCode() is
and although I have not yet explained what it is, it is enough to know that hashCode() is
implemented, so the value is determined both by a person’s first and last name. Finally you
implemented, so the value is determined both by a person’s first and last name. Finally you
should note, that the class implements the interface Comparable<Person>, such that Person
should note, that the class implements the interface Comparable<Person>, such that Person
objects first are ordered after the last name and then by the first name.
objects first are ordered after the last name and then by the first name.

Add the following method to the main class:


Add the following method to the main class:

private static List<Person> createList()


private static List<Person> createList()
{
{
ArrayList<Person> list = new ArrayList();
ArrayList<Person> list = new ArrayList();
list.add(new Person("Karl", "Jensen"));
list.add(new Person("Karl", "Jensen"));

Download free eBooks at bookboon.com


Click on the ad to read more
151
151
151
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVA 4:
4: JAVA’S
JAVA’S TYPE
JAVACOLLECTION
AND TYPE SYSTEM
SYSTEM
CLASSES Collection
AND COLLECTION CLASSES ColleCtIon classes
Classes
AND COLLECTION CLASSES
AND COLLECTION CLASSES ColleCtIon
ColleCtIon Classes
Classes

list.add(new Person("Agnes", "Jensen"));


list.add(new
list.add(new Person("Agnes",
Person("Agnes", "Jensen"));
"Jensen"));
list.add(new Person("Esben", "Hansen"));
list.add(new
list.add(new Person("Esben",
Person("Esben", "Hansen"));
"Hansen"));
list.add(new Person("Abelone", "Andersen"));
list.add(new
list.add(new Person("Abelone",
Person("Abelone", "Andersen"));
"Andersen"));
list.add(new Person("Knud", "Jensen"));
list.add(new
list.add(new Person("Knud",
Person("Knud", "Jensen"));
"Jensen"));
list.add(new Person("Valborg", "Andesern"));
list.add(new
list.add(new Person("Valborg",
Person("Valborg", "Andesern"));
"Andesern"));
list.add(new Person("Frede", "Jensen"));
list.add(new
list.add(new Person("Frede",
Person("Frede", "Jensen"));
"Jensen"));
list.add(new Person("Olga", "Hansen"));
list.add(new
list.add(new Person("Olga",
Person("Olga", "Hansen"));
"Hansen"));
list.add(new Person("Karlo", "Andersen"));
list.add(new
list.add(new Person("Karlo",
Person("Karlo", "Andersen"));
"Andersen"));
list.add(new Person("Gudrun", "Hansen"));
list.add(new
list.add(new Person("Gudrun",
Person("Gudrun", "Hansen"));
"Hansen"));
return list;
return
return list;
list;
}
}
}

Then
Then you
you should
should add
add a method, that prints the content of af collection, when the objects
Then you
Then you should add aaa method,
should add method, that
method, that prints
that prints the
prints the content
the content
content ofof af
of af collection,
af collection, when
collection, when the
when the objects
the objects
objects
must
must be
be printed
printed as
as a comma separated list on the same line:
must be
must be printed as aaa comma
printed as comma separated
comma separated list
separated list on
list on the
on the same
the same line:
same line:
line:
private static void print(Collection<?> collection)
private
private static
static void
void print(Collection<?>
print(Collection<?> collection)
collection)
{
{
{
}
}
}

Write
Write two methods, that from a list creates a HashSet and a TreeSet:
Write two
two methods,
methods, that
that from
from aa list
list creates
creates aa HashSet
HashSet and
and aa TreeSet:
TreeSet:
private static Set<Person> createTreeSet(List<Person> list)
private
private static Set<Person> createTreeSet(List<Person>
static Set<Person> list)
createTreeSet(List<Person> list)
{
{
{
}
}
}

private static Set<Person> createHashSet(List<Person> list)


private
private static
static Set<Person>
Set<Person> createHashSet(List<Person>
createHashSet(List<Person> list)
list)
{
{
{
}
}
}

Finally
Finally you should test the methods in the main() method:
Finally you
you should
should test
test the
the methods
methods in
in the
the main()
main() method:
method:
public static void main(String[] args)
public
public static
static void
void main(String[]
main(String[] args)
args)
{
{
{
List<Person> list = createList();
List<Person>
List<Person> list
list == createList();
createList();
print(list);
print(list);
print(list);
Set<Person> set1 = createHashSet(list);
Set<Person>
Set<Person> set1
set1 =
= createHashSet(list);
createHashSet(list);
print(set1);
print(set1);
print(set1);
Set<Person> set2 = createTreeSet(list);
Set<Person>
Set<Person> set2
set2 =
= createTreeSet(list);
createTreeSet(list);
print(set2);
print(set2);
print(set2);
}
}
}

Download free eBooks at bookboon.com


152
152
152
152
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Collection
ColleCtIonclasses
Classes

9.6
9.6 HASHMAP
HASHMAPAND
ANDTREEMAP
TREEMAP
AAMap
Mapisisasasmentioned
mentioneda acollection
collectionconsisting
consistingofofkey/value
key/valuepairs,
pairs,where
wherethe
thekey
keydetermines
determines
the
thevalue.
value.An
Anexample
exampleofofa aconcrete
concreteclass
classisisa aHashMap,
HashMap,which
whichisisa ageneric
genericclass
classparameterized
parameterized
by
bytwo
twoparameters,
parameters,one
onefor forthethekey
keyand
andthe theother
otherfor
forthe
thevalue.
value.

InInthe
thefollowing
followingexample,
example,the
theclass
classPerson
Personisisthe
thesame
sameasasininthe
theprevious
previousexercise,
exercise,and
andthe
the
same
sameapplies
appliestotothe
themethod
methodcreateList().
createList().The
Thefollowing
followingmethod
methodcreates
createsa aHashMap
HashMapwhere
where
the
thekey
keyisisa aString,
String,while
whilethe
thevalue
valueisisa aPerson
Personobject.
object.The
Thevalue
valueofofthe
thekey
keyisisthe
theperson’s
person’s
first
firstname:
name:

private static void test06()


{
Map<String, Person> map = new HashMap();
List<Person> list = createList();
for (Person p : list) map.put(p.getFirstname(), p);
for (String key : map.keySet()) System.out.println(key + "\t" + map.get(key));
}

Note
Notehow howtotoadd
addobjects
objectstotoa aHashMap
HashMapand andyouyouhashastototell
tellboth
boththethekey
keyand
andvalue.
value.InInthis
this
case it is assumed that all people have different first names. Finally, note how to
case it is assumed that all people have different first names. Finally, note how to traverse the traverse the
data
datastructure.
structure.First
Firstyou
yougetgeta aSet
Setwith
withallallkeys,
keys,which
whichyou youcan
cantraverse
traverseand
andusing
usingthe
thekeykey
and the method get() you can determine the value associated with the key.
and the method get() you can determine the value associated with the key. If you performs If you performs
the
themethod,
method,you youget
getthe
theresult:
result:

Knud Knud Jensen


Karlo Karlo Andersen
Agnes Agnes Jensen
Olga Olga Hansen
Karl Karl Jensen
Frede Frede Jensen
Abelone Abelone Andersen
Valborg Valborg Andesern
Gudrun Gudrun Hansen
Esben Esben Hansen

The
Thename
nameofofa aHashMap
HashMapsayssaysthat
thatthe
thekeys
keysinternally
internallyare
arestored
storedinina aHashSet.
HashSet.There
Thereisis
another
anotherimplementation
implementationofofa aMapMapcalled
calleda aTreeMap,
TreeMap,and andthe
thename
namehere
hereisisderived
derivedfrom,
from,
that
that the keys this time is stored in a TreeSet, which in turn means that if you traversea a
the keys this time is stored in a TreeSet, which in turn means that if you traverse
TreeMap,
TreeMap,the
theelements
elementswill
willbebesorted
sortedbybythe
thekey.
key.

Download free eBooks at bookboon.com


153
153
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES
CLASSES Collection
ColleCtIon classes
Classes
AND COLLECTION CLASSES ColleCtIon Classes

IfIf you in the above method replaces the first statement with the following
If you
you in
in the
the above
above method
method replaces
replaces the
the first
first statement
statement with
with the
the following
following

Map<String,
Map<String, Person>
Person> map
map =
= new
new TreeMap();
TreeMap();

and
and the
and the method
method isis
the method executed
is executed the
executed the result
the result is:
result is:
is:

Abelone
Abelone Abelone
Abelone Andersen
Andersen
Agnes
Agnes Agnes
Agnes Jensen
Jensen
Esben
Esben Esben
Esben Hansen
Hansen
Frede
Frede Frede
Frede Jensen
Jensen
Gudrun
Gudrun Gudrun
Gudrun Hansen
Hansen
Karl
Karl Karl
Karl Jensen
Jensen
Karlo
Karlo Karlo
Karlo Andersen
Andersen
Knud
Knud Knud
Knud Jensen
Jensen
Olga
Olga Olga
Olga Hansen
Hansen
Valborg
Valborg Valborg
Valborg Andesern
Andesern

Download free eBooks at bookboon.com


Click on the ad to read more
154
154
154
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Collection
ColleCtIonclasses
Classes

9.7
9.7 PRIORITYQUEUE
PRIORITYQUEUE
I Ihave
haveabove
abovementioned
mentioneda aqueue,queue,and
anda apriorityqueue
priorityqueueisisa aqueue,
queue,where
wherethetheelements
elementsare are
added
addedaccording
accordingtotoa apriority,
priority,that
thatmeans
meansthat
thatthe
theelements
elementsare areorderede
orderedeininthe
thequeue.
queue.TheThe
order
ordercancanbebedefined
definedby bythe
thenatural
naturalordering,
ordering,that
thatisisthe
theordering
orderingdefined
definedbybya aclass
classthat
that
implements
implementsComparable,
Comparable,ororby bya aComparator
Comparatorprovided
providedatatconstruction
constructiontime.
time.IfIfa apriority
priority
queue
queueisisrelying
relyingon onnatural
naturalordering,
ordering,objects
objectsinserted
insertedininthethequeue
queuemust
mustbebedefined
definedby bya a
class
classthat
thatimplements
implementsComparable.
Comparable.WhenWhenelements
elementsareareretrieved
retrievedfrom
fromthe
thequeue
queue(for(forexample
example
with
withpoll()),
poll()),ititisisthe
theleast
leastelement
elementwith
withrespect
respecttotothe
thespecified
specifiedordering
orderingthat
thatisisretrieved.
retrieved.

The
Theclass
classisisimplemented
implementedby bya aheap,
heap,that
thatisisa adata
datastructure,
structure,which
whichactsactsasasa abinary
binarytree,
tree,
but
butsuch
suchthat
thatthe
theelement
elementtotobeberetrived
retrivednext
nextisisa athe
theroot.
root.ItItisisananefficient
efficientdata
datastructure,
structure,
and
anda aPriorityQueu
PriorityQueuisisthen
thenananefficient
efficientcollection.
collection.

EXERCISE
EXERCISE12
12
InInthis
thisexercise
exerciseyou
youshould
shouldtesttestthe
theclass
classPriortyQueue.
PriortyQueue.Create
Createa aprogram,
program,that
thatyou
youcan
cancall
call
PriorityProgram.
PriorityProgram.AddAddthetheclass
classPerson
Personfrom
fromexercise
exercise11
11totothe
theproject.
project.Also
Alsotake
takea acopy
copyofof
the
themethod
methodcreateList()
createList()ininexercise
exercise1111and
andpaste
pastethe
themethod
methodtotothethemain
mainclass.
class.

Add
Adda amethod
methodprint()
print()

private static void print(Queue<Person> q)


{
}

when
whenthethemethod
methodmust
mustremove
removeallallelements
elementsfrom
fromthe
thequeue
queue(poll()
(poll()allallelements)
elements)and
andprint
print
the elements as a comma separated list on a single line.
the elements as a comma separated list on a single line.

Next
Nextadd
adda amethod
methodtest1()
test1()

private static void test1(List<Person> list)


{
}

that creates a PriorityQueue<Person> with natural ordering. The method must add all elements
that creates a PriorityQueue<Person> with natural ordering. The method must add all elements
in the list to the queue, and then the method should call print() to print the queue.
in the list to the queue, and then the method should call print() to print the queue.

In the main() method you must create a list (by createList()) and call test1().
In the main() method you must create a list (by createList()) and call test1().

Download free eBooks at bookboon.com


155
155
JAVA
JAVA4: JAVA’S TYPE SYSTEM
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION CLASSES Collection classes
AND COLLECTION CLASSES
COLLECTION CLASSES ColleCtIon
ColleCtIon Classes
Classes

You
Youshould then write aamethod
You should
should then
then write
write a method
method

private
private static
static void
void test2(List<Person>
test2(List<Person> list)
list)
{
{
}
}

that
thatdo
that doexactly
do exactlythe
exactly thesame,
the same,but
same, butthis
but thistime
this timetiltil
time tilordering
orderingmust
ordering mustbe
must bedefined
be definedby
defined byaaacomparator,
by comparator,and
comparator, and
and
the
the comparator should be defined by a lambda expression. The syntax to create a queueis:is:
the comparator
comparator should
shouldbe
be defined
defined by
bya alambda
lambda expression.
expression.The
Thesyntax
syntaxto
to create
createa aqueue
queue is:

Queue<Person>
Queue<Person> qq =
= new
new PriorityQueue<Person>(list.size(),
PriorityQueue<Person>(list.size(),
(Person
(Person p1, Person p2)
p1, Person p2) ->
-> p1.getLastname().compareTo(p2.getLastname()));
p1.getLastname().compareTo(p2.getLastname()));

ToTouse
To useaaacomparator
use comparatorthe
comparator theconstructor
the constructortoto
constructor tothe
theclass
the classPriorityQueue
class PriorityQueueneeds
PriorityQueue needstwo
needs twoparameters.
two parameters.The
parameters. The
The
first
firstparameter
parameter is
isananint
intand
and is
isan
an initial
initialcapacity.
capacity. ItIthas
hasnothing
nothing to
todo
do with
with the
the
first parameter is an int and is an initial capacity. It has nothing to do with the comparator,comparator,
comparator,
and
andinin
and inprinciple
principleyou
principle youcan
you canuse
can useany
use anypositive
any positivenumber,
positive number,but
number, butthe
but theidea
the ideawith
idea withan
with aninitial
an initialcapacity
initial capacityisis
capacity istoto
to
avoid
avoid the
the container
container toto be
be expanded.
expanded. The
The interface
interface Comparator<Person>
Comparator<Person> defines
avoid the container to be expanded. The interface Comparator<Person> defines one methoddefines one
onemethod
method

int
int compare(Person
compare(Person p1,
p1, Person
Person p2)
p2)

and
and toto
and to define
define this
define this method
this method asas
method as aaa lambda
lambda expression
lambda expression you
expression you needs
you needs an
needs an expression
an expression with
expression with two
with two
two
arguments.
arguments. You should note, the use of the parentheses around the arguments.
arguments. You should note, the use of the parentheses around the arguments. When you
You should note, the use of the parentheses around the arguments. When
When you
you
have
havewritten
written the
themethod
method you
you must
must test
testititfrom
from the
themain()
main()
have written the method you must test it from the main() method. method.
method.

Finally
Finallyyou
Finally youshould
you shouldwrite
should writeaaamethod
write method
method

private
private static
static void
void test3(List<Person>
test3(List<Person> list)
list)
{
{
}
}

that
that do
thatdo exactly
doexactly the
exactlythe same
sameasas
thesame test2(),
astest2(), but
test2(),but this
butthis time
timetiltil
thistime elements
tilelements must
elementsmust be
mustbe ordered
beordered by
orderedby the
bythe first
thefirst name.
firstname.
name.

IfIf the
Ifthe program
programisis
theprogram executed,
isexecuted, the
executed,the result
theresult should
resultshould be:
shouldbe:
be:

Abelone
Abelone Andersen,
Andersen, Karlo
Karlo Andersen,
Andersen, Valborg
Valborg Andesen,
Andesen, Esben
Esben Hansen,
Hansen,
Gudrun
Gudrun Hansen, Olga Hansen, Agnes Jensen, Frede Jensen, Karl
Hansen, Olga Hansen, Agnes Jensen, Frede Jensen, Karl Jensen,
Jensen,
Knud Jensen
Knud Jensen
Abelone
Abelone Andersen,
Andersen, Karlo
Karlo Andersen,
Andersen, Valborg
Valborg Andesen,
Andesen, Esben
Esben Hansen,
Hansen,
Olga
Olga Hansen, Gudrun Hansen, Frede Jensen, Agnes Jensen, Knud
Hansen, Gudrun Hansen, Frede Jensen, Agnes Jensen, Knud Jensen,
Jensen,
Karl Jensen
Karl Jensen
Abelone
Abelone Andersen,
Andersen, Agnes
Agnes Jensen,
Jensen, Esben
Esben Hansen,
Hansen, Frede
Frede Jensen,
Jensen, Gudrun
Gudrun Hansen,
Hansen,
Karl Jensen, Karlo Andersen, Knud Jensen, Olga Hansen, Valborg Andesen
Karl Jensen, Karlo Andersen, Knud Jensen, Olga Hansen, Valborg Andesen

Download free eBooks at bookboon.com


156
156
156
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection classes

9.8 THE ALGORITMS


Java’s collection API consist also of many methods, that can be used in practical programming
and are methods that you often needs. They are members in the class Collections, and are
all static methods whose first argument is the collection on which the operation is to be
performed. Most of the methods operates on a List, but a few operates on a arbitrary
Collection. The algorithms or methods are used for:

-- sorting
-- shuffling
-- data manipulation
-- searching
-- composition
-- finding extreme values

SORTING

The class Collections has a method sort(), that can be used to sort a List. It is a highly effective
sorting method that use an algorithm called merge sort. There is two versions, where the one
use the natural ordering, while the other use a comparator. The following method shows
how to use sort() to sort Person objects in natural order:

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

Download free eBooks at bookboon.com


Click on the ad to read more
157
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA 4:
4: JAVA’S TYPE SYSTEM
AND
JAVA 4: JAVA’S
JAVA’S TYPE
COLLECTION SYSTEM
CLASSES
TYPE SYSTEM Collection classes
AND COLLECTION
AND COLLECTION CLASSES
COLLECTION CLASSES
CLASSES ColleCtIon
ColleCtIon Classes
Classes
AND ColleCtIon Classes

private
private static void test07()
private static
static void
void test07()
test07()
{
{
{
List<Person>
List<Person> list1
list1 =
= createList();
List<Person> list1 = createList();
createList();
List<Person>
List<Person> list2 = new LinkedList();
List<Person> list2 = new
list2 = new LinkedList();
LinkedList();
for (Person
for (Person
(Person pp :
p : list1)
list1) list2.add(p);
: list1) list2.add(p);
for list2.add(p);
Collections.sort(list1);
Collections.sort(list1);
Collections.sort(list1);
print(list1);
print(list1);
print(list1);
Collections.sort(list2);
Collections.sort(list2);
Collections.sort(list2);
print(list2);
print(list2);
print(list2);
}
}
}

Youshould
should note the syntax (and simpler
simpleritit may not be), and you should note that
thatitit also
You shouldnote
You notethe
thesyntax
syntax(and
(andsimpler itmay
maynot
notbe),
be),and
andyou
youshould
shouldnote
notethat italso
also
is possible
isispossible to sort
possibletotosort a LinkedList.
sortaaLinkedList.
LinkedList.

As another
Asanother
As example
anotherexample the
examplethe following
thefollowing method
followingmethod sorts
sortsaaalist
methodsorts list with
listwith random
withrandom integers
randomintegers and
integersand prints
andprints how
printshow
how
many milliseconds
manymilliseconds
many the
millisecondsthe sorting
thesorting has
sortinghas taken:
hastaken:
taken:

private
private static void test08(int n)
private static
static void
void test08(int
test08(int n) n)
{
{
{
List<Integer>
List<Integer> list = new ArrayList();
List<Integer> list
list =
= new
new ArrayList();
ArrayList();
for (int
for (int
(int ii
i == 0;
= 0; i
0; i < n; ++i) list.add(rand.nextInt());
for i <
< n;
n; ++i)
++i) list.add(rand.nextInt());
list.add(rand.nextInt());
long
long t1
t1 =
= Calendar.getInstance().getTimeInMillis();
Calendar.getInstance().getTimeInMillis();
long t1 = Calendar.getInstance().getTimeInMillis();
Collections.sort(list,
Collections.sort(list, (Integer
(Integer a,
a, Integer
Integer b)
b) ->
-> -a.compareTo(b));
-a.compareTo(b));
Collections.sort(list, (Integer a, Integer b) -> -a.compareTo(b));
long
long t2
t2 =
= Calendar.getInstance().getTimeInMillis();
Calendar.getInstance().getTimeInMillis();
long t2 = Calendar.getInstance().getTimeInMillis();
System.out.println(t2
System.out.println(t2 – – t1);
t1);
System.out.println(t2 – t1);
}
}
}

Onmy
my machine
machineI IIget
get the result 3349 (about three seconds)
seconds)toto sort 10 million numbers.
On mymachine
On getthe
theresult
result3349
3349(about
(aboutthree
threeseconds) tosort
sort10
10million
millionnumbers.
numbers.

SHUFFLING
SHUFFLING
SHUFFLING
SHUFFLING
There
Thereisis
There also
alsoaaamethod
isalso method
methodtoto shuffle
shuffleaaacollection
toshuffle collection
collectionofof objects.
ofobjects. The
objects.The method
methodisis
Themethod called
iscalled shuffle(),
calledshuffle(), and
shuffle(),and
and
the parameter
theparameter
the is a List<T>.
parameterisisaaList<T>. It is obviously
List<T>.ItItisisobviously
obviouslynotnot
notthethe most
themost interesting
mostinteresting method,
interestingmethod,
method,butbut I have
butI Ihave
have
neverthelessininprevious
nevertheless previous exampleswritten
written myown own shufflemethod,
method, andififyou you need,it’s it’s
nevertheless in previousexamples
examples writtenmy my ownshuffle
shuffle method,and and if youneed,
need, it’s
goodtotoknow
good know thatthere
there is a method,whichwhich is justtotoapply.
apply.
good to knowthat that thereisisaamethod,
method, whichisisjust just to apply.

private
private static void test09()
private static
static void
void test09()
test09()
{
{
{
List<Integer>
List<Integer> list =
List<Integer> list
list ==
new
new ArrayList(Arrays.asList( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29));
new ArrayList(Arrays.asList( 2,
ArrayList(Arrays.asList( 2, 3,
3, 5,
5, 7,
7, 11,
11, 13,
13, 17,
17, 19,
19, 23,
23, 29));
29));
print(list);
print(list);
print(list);
Collections.shuffle(list);
Collections.shuffle(list);
Collections.shuffle(list);
print(list);
print(list);
print(list);
}
}
}

Download free eBooks at bookboon.com


158
158
158
158
JAVA4:4:JAVA’S
JAVA JAVA’S TYPESYSTEM
SYSTEM
JAVA 4: JAVA’STYPE
TYPE SYSTEM
ANDCOLLECTION
AND COLLECTIONCLASSES
CLASSES ColleCtIonclasses
Collection Classes
AND COLLECTION CLASSES ColleCtIon Classes

DATA
DATA MANIPULATION
DATAMANIPULATION
MANIPULATION
The
The Collections
TheCollections class
Collectionsclass defines
classdefines the
definesthe following
thefollowing methods
methodstoto
followingmethods manipulate
tomanipulate the
manipulatethe elements
elementsinin
theelements inaaaList:
List:
List:

---- reverse(),
reverse(),
reverse(),thatthat reverse
thatreverse
reversethe the order
orderofof
theorder all
ofall elements
elementsinin
allelements inaaaList.
List.
List.
---- fill(),
fill(), that
fill(),that overrides
thatoverrides
overridesall all elements
allelements in a
elementsininaaList List with
Listwith a specified
withaaspecified value,
specifiedvalue, and
value,and the
andthe method
themethod
method
is usefull
isisusefull to initialize
usefulltotoinitialize a
initializeaaList. List.
List.
---- copy()
copy()
copy()thatthat copy
thatcopy
copyall all elements
elementsinin
allelements one
inone
oneListList
Listtoto another
toanother List.
anotherList. The
List.The destination
Thedestination List
destinationList must
Listmust
must
bebe at least as long as the source. If it is longer, the remaining
be at least as long as the source. If it is longer, the remaining elements in the
at least as long as the source. If it is longer, the remaining elements
elements in
in the
the
destination
destination
destinationList List
Listareare unchanged.
areunchanged.
unchanged.
---- swap(),
swap(),
swap(),that that swaps
thatswaps
swapstwo two elements
elementsinin
twoelements inaaaList.
List.
List.
---- addAll(),
addAll(),
addAll(),that that
thataddsadds
addsall all elements
elementsinin
allelements inan an array
arraytoto
anarray toaaaCollection.
Collection.
Collection.
private
private static
static void
void test10()
test10()
{
{
List<Integer>
List<Integer> list1
list1 =
= new
new ArrayList();
ArrayList();
Collections.addAll(list1,
Collections.addAll(list1, 2, 2, 3,
3, 5,
5, 7,
7, 11,
11, 13,
13, 17,
17, 19,
19, 23,
23, 29);
29);
print(list1);
print(list1);
Collections.fill(list1,
Collections.fill(list1, 5);
5);
print(list1);
print(list1);
List<Integer>
List<Integer> list2
list2 =
= new
new ArrayList();
ArrayList();
Collections.addAll(list2,
Collections.addAll(list2, 2, 3,
2, 3, 5,
5, 7,
7, 11,
11, 13,
13, 17,
17, 19,
19, 23,
23, 29,
29, 31,
31, 37);
37);
Collections.copy(list2, list1);
Collections.copy(list2, list1);
print(list2);
print(list2);
}
}

2
2 3
3 5
5 7
7 11
11 1313 17
17 19
19 23
23 29
29
5
5 5
5 5
5 5
5 5
5 5 5
5 5 5
5 5 5
5 5
5
5 5
5 5
5 5
5 5
5 55 55 5
5 55 5
5 31
31 37
37

SEARCHING
SEARCHING
SEARCHING
The
The class
Theclass Collections
classCollections implements
Collectionsimplements also
implementsalso binary
alsobinary search:
binarysearch:
search:
<T>
<T> int
int binarySearch(List<?
binarySearch(List<? extends
extends Comparable<?
Comparable<? super
super T>>
T>> list,
list, T
T key)
key)
<T>
<T> int
int binarySearch(List<?
binarySearch(List<? T>
T> list, T key, Comparator<? super T> cmp)
list, T key, Comparator<? super T> cmp)

As
AsI IIhave
have mentioned
havementioned binary
mentionedbinary search,
binarysearch, there
thereisis
search,there not
isnot more
moretoto
notmore say
sayofof
tosay ofit,it, but
butofof
it,but course
courseitit
ofcourse itisis good
isgood
good
As
to know that it already exists, so it is not necessary to implement it.
totoknow
knowthatthatititalready
alreadyexists,
exists,sosoititisisnot
notnecessary
necessarytotoimplement
implementit.it.

COMPOSITION
COMPOSITION
COMPOSITION
This group
groupofof
Thisgroup methods
ofmethods contains
methodscontains two
containstwo methods
twomethods
methods
This

- frequency(), that counts the number


numberofof times
timesaaaspecified
specified element occurs
occursinin
inaaaCollection.
Collection.
--- frequency(),that
frequency(), thatcounts
countsthe
thenumber oftimes specifiedelement
elementoccurs Collection.
- disjoint(), that determines whether two Collection of objects are disjoint and then
--- disjoint(),that
disjoint(), thatdetermines
determineswhether
whethertwo
twoCollection
Collectionofofobjects
objectsare
aredisjoint
disjointandandthen
then
has
hasnono elements
noelements in common.
elementsinincommon.
common.
has

Download free eBooks at bookboon.com


159
159
159
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Collection
ColleCtIon classes
Classes

The following method shows to use this methods:

private static void test11()


{
List<Integer> list1 = new ArrayList();
Collections.addAll(list1, 11, 2, 3, 5, 7, 3, 11, 13, 17, 19, 3);
System.out.println(Collections.frequency(list1, 2));
System.out.println(Collections.frequency(list1, 3));
System.out.println(Collections.frequency(list1, 11));
System.out.println(Collections.frequency(list1, 12));
List<Integer> list2 = new ArrayList();
Collections.addAll(list2, 2, 4, 8, 16, 32, 64);
List<Integer> list3 = new ArrayList();
Collections.addAll(list2, 4, 8, 16, 32, 64);
System.out.println(Collections.disjoint(list1, list2));
System.out.println(Collections.disjoint(list1, list3));
}

Download free eBooks at bookboon.com


Click on the ad to read more
160
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION
JAVA CLASSES
4: JAVA’S TYPE SYSTEM Collection classes
AND COLLECTION CLASSES ColleCtIon Classes

1
3
2
0
false
true

FINDING
FINDINGEXTREME
EXTREMEVALUES
VALUES
That
Thatisistwo
twosimple
simplemethods
methodsmin()
min()and
andthe
themax()
max()that,
that,respectively,
respectively,determines
determinesthe
theminimum
minimum
and
and maximum element in a Collection(). Both methods exists in two versions. The onetakes
maximum element in a Collection(). Both methods exists in two versions. The one takes
only a Collection as parameter and returns the minimum (or maximum) element
only a Collection as parameter and returns the minimum (or maximum) element according according
totothe
theelements’
elements’natural
naturalordering.
ordering.The
Theother
otheralso
alsohas
hasComparator
Comparatorasasaaparameter.
parameter.

EXERCISE
EXERCISE12
12
Write
Writeaaprogram,
program,that
thatyou
youcan
cancall
callMinMax.
MinMax.The Themain()
main()method
methodmust
mustcreate
createan
anArrayList
ArrayList
initialized
initialized with 10 random numbers of the type Double. After the list is created, itshould
with 10 random numbers of the type Double. After the list is created, it should
be printed.
be printed.

You
Youmust
mustthen
thenuse
usethe
themethods
methodsmin()
min()and
andmax()
max()totoprints,
prints,respectively,
respectively,the
thesmallest
smallestvalue
value
and the biggest value in the list.
and the biggest value in the list.

Finally
Finallyyou
youshould
shouldduduthe
thesamme,
samme,but
butthis
thistime
timethe
thenumbers
numbersmust
mustbe
becompared
comparedwith
withtheir
their
numerical deviation from 0.5.
numerical deviation from 0.5.

The
Theresult
resultcould
couldbe:
be:

0.46732756489906613
0.6364287975820527
0.41794515249897457
0.4886474458162239
0.24707263700220072
0.30797749425175236
0.9921562698882159
0.23247661998977032
0.40622432064377734
0.5122684891300776

0.23247661998977032
0.9921562698882159
0.4886474458162239
0.9921562698882159

Download free eBooks at bookboon.com


161

161
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Annotation
annotatIon

10
10 ANNOTATION
ANNOTATION
Annotations,
Annotations,areareaaform
formofofmetadata,
metadata,andandthen
thendata
dataabout
aboutaaprogram
programthat
thatisisnot
notpart
partofofthe
the
program
programitself.
itself.Annotations
Annotationshave
havenonodirect
directeffect
effectononthe
theexecution
executionofofthe
theprogram,
program,but butititisis
aaway
waytotowrite
writeinformation
informationtotothe
thecompiler,
compiler,that
thatcancanuse
useannotations
annotationstotodetect
detecterrors,
errors,but
but
there
thereare
arealso
alsoannotations
annotationsthat
thatare
areexamined
examinedatatruntime.
runtime.Furthermore,
Furthermore,there
thereisissome
somesoftware
software
tools
toolsthat
thatuse
useannotations
annotationstotogenerate
generatecode.
code.Through
Throughthe thebooks
booksyou
youwill
willsee
seeseveral
severaluses
usesofof
annotations
annotationsbutbutIIwill
willonly
onlyshow
showoneoneininthis
thisbook.
book.Consider
Consideragain
againthe
theclass
classPerson,
Person,where
where
IIhave
haveonly
onlyshown
shownthethepart
partofofthe
thecode
codethat
thatisisrelated
relatedtotoannotations
annotations

public class Person implements Comparable<Person>


{

@Override
public String toString()
{
return firstname + " " + lastname;
}

@Override
public boolean equals(Object obj)
{
if (obj == null) return false;
if (getClass() == obj.getClass())
{
Person pers = (Person)obj;
return firstname.equals(pers.firstname) && lastname.equals(pers.lastname);
}
return false;
}

@Override
public int hashCode()
{
return firstname.hashCode() ^ lastname.hashCode();
}

Download free eBooks at bookboon.com


162
162
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE
AND COLLECTION SYSTEM
CLASSES Annotation
AND COLLECTION CLASSES annotatIon

@Override
public int compareTo(Person pers)
{
if (lastname.equals(pers.lastname)) return firstname.compareTo(pers.firstname);
return lastname.compareTo(pers.lastname);
}
}

In front of four of the methods I have written @Override. It is an annotation. It tells


the compiler that the method is overridden from the base class or an interface, and the
compiler will report an error if, for example, I have spelled the name of a method wrong.
It remove a source of errors from the code, because you else may believe that a method is
been overridden without it actually is. It is therefore recommended to use this annotation
in front of all methods that are overridden.

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

Download free eBooks at bookboon.com


Click on the ad to read more
163
163
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
JAVA
JAVA 4: JAVA’S
JAVA’S TYPE
4:JAVA’S
4: TYPE SYSTEM
SYSTEM
AND
JAVA
AND 4: JAVA’STYPE
COLLECTION
COLLECTIONTYPESYSTEM
CLASSES
SYSTEM
CLASSES
paCkages
paCkages
ANDCOLLECTION
AND COLLECTIONCLASSES
CLASSES paCkages
Packages
AND COLLECTION CLASSES paCkages

11
11
11 PACKAGES
PACKAGES
PACKAGES
11 PACKAGES
A Java program consists of many classes and interfaces. First, the classes that you yourself
AA
A
A
Java
Java
Java
Java
program
program
program
program
consists
consists
consists
consists ofof
of
of
many
many
many
many
classes
classes
classes
classes
and
and
and
and
interfaces.
interfaces.
interfaces.
interfaces.
First,
First,
First,
First,
the
the
the
the
classes
classes
classes
classes
that
that
that
that
you
you
you
you
yourself
yourself
yourself
yourself
write,
write, and
and also
also the
the classes
classes that
that come
come from
from the
the Java
Java API.
API. To
To avoid
avoid name
name matches
matches and
and to
write,
write,
write, and
and
and also
also
also the
the
the classes
classes
classes that
that
that come
come
come from
from
from the
the
the Java
Java
Java API.
API.
API. To
To
To avoid
avoid
avoid name
name
name matches
matches
matches and
and
and toto
to
to
increase
increase clarity,
clarity, classes
classes and
and other
other types
types are
are placed
placed in
in packages.
packages. For
For example
example are
are Java’s
Java’s own
own
increase
increase
increase clarity,
clarity, classes
clarity,classes
classes and
and
andotherother types
types
othernumbertypesare are
are placed
placed
placed in packages.
ininpackages.
packages. For
For
For example
example
example are
are Java’s
areJava’s
Java’s own
own
own
classes
classes divided
divided into
into aa very
very large
large number of
of packages.
packages. The
The basic
basic package
package is
is called
called java.lang,
java.lang,
classes
classes
classes divided
divided into
into
divided into a a very
very
a very large
large
large number
number
number of
of
of packages.
packages.
packages. The basic
The basic package
package is called java.lang,
is calledclasses
java.lang,
and
and it
it contains
contains all
all the
the basic
basic classes
classes such
such as
as String,
String, System,
System, Object,
Object, the
the wrapper
wrapper classes etc.
etc.
and
and
and itit
it contains
contains
contains all
all
all the
the
the basic
basic
basic classes
classes
classes such
such
such as
as
as String,
String,
String, System,
System,
System, Object,
Object,
Object, the
the
the wrapper
wrapper
wrapper classes
classes
classes etc.
etc.
etc.
The
The classes
classes in
in this
this package
package is
is immediately
immediately available
available for
for the
the runtime
runtime system,
system, and
and you
you do
do not
not
The
The
The classes
classes
classes in this
ininthis
this package
package
package is immediately
isisimmediately
immediately available
available
available for
for
for the
the
the runtime
runtime
runtime system,
system,
system, and
and
and you
you
you do
do
do not
not
not
have
have to
to do
do anything
anything special
special to
to use
use these
these classes.
classes. Things
Things are
are different
different with
with classes
classes in
in other
other
have
have
have to
totodo do
doAs anything
anything
anything special
special
special to
totouseuse
use these
these
these classes.
classes.
classes. Things
Things
Things are
are different
aredifferent
different with
with classes
withisclasses
classes in other
ininother
other
packages.
packages. As an
an example,
example, II have
have often
often used
used the
the class
class Random.
Random. This
This class
class is in
in the
the package
package
packages.
packages.
packages. As
As anan
As an as example,
example,
example, I I have
have
I have often
often
often used
used the
the
used the class
class
class Random.
Random. This
This
Random. This class
class
class isisinin the
the
is in the package
package
package
java.util,
java.util, which
which as the
the name
name says
says is
is aa package
package of
of miscellaneous
miscellaneous classes
classes or
or tools.
tools. This
This means
means
java.util,
java.util,
java.util, which
which
which asas
as the
the
the name
name
name says
says
says isis
isa a
a package
package
package ofof
of miscellaneous
miscellaneous
miscellaneous classes
classes
classes or
or
or tools.
tools.
tools. This
This
This means
means
means
that
that the
the full
full name
name of
of the
the class
class is
is java.util.Random.
java.util.Random. If
If you
you have
have to
to create
create an
an object,
object, you
you can
can
that
that
that the
the
the full
full
full name
name
name of
ofofthethe
the class
class
class is java.util.Random.
isisjava.util.Random.
java.util.Random. If you
IfIfyou
you have
have
have to create
totocreate
create anan
an object,
object,
object, you
you
you can
can
can
therefore
therefore write:
write:
therefore
therefore write:
thereforewrite:
write:
java.util.Random
java.util.Random rand
rand =
= new
new java.util.Random();
java.util.Random();
java.util.Random
java.util.Random rand
rand =
= new
new java.util.Random();
java.util.Random();

When
When it is difficult to write (you has to write much), and it also makes the code harder to
When
When
When itit
it
itisis
is
is
difficult
difficult
difficult
difficulttoto
to
to
write
write
write
write
(you
(you
(you
(you
has
has
has
hastoto
to
to
write
write
write
write
much),
much),
much),
much),
and
and
and
anditit
it
it
also
also
also
also
makes
makes
makes
makes
the
the
the
the
code
code
code
code
harder
harder
harder
hardertoto
to
to
read,
read, you
you can
can specify
specify an
an import
import statement:
statement:
read,
read,you
you can
can specify
specify ananimport
import statement:
statement:
read, you can specify an import statement:
import
import java.util.Random;
java.util.Random;
import
import java.util.Random;
java.util.Random;

which
which
which tells
tells what
tellswhat the
whatthe class
theclass Random
classRandom means,
Randommeans, and
andsoso
means,and you
soyou can
youcan just
canjust write
justwrite the
writethe class
theclass name:
classname:
name:
which
which tells
tells what
what the
the class
class Random
Random means,
means, and
and so
so you
you can
can just
just write
write the
the class
class name:
name:
Random
Random rand
rand =
= new
new Random();
Random();
Random
Random rand
rand =
= new
new Random();
Random();

One
One
One should
should
should note
note
note that
that
thatitit
itisis
is also
also
also the
the
the only
only
only thing
thing
thing that
that
that anan
an import
import
import means
means
means and
and
and itit
itisis
is not
not
nota aaaquestion
question
question
One
One should
should note
note that
that it
it is
is also
also the
the only
only thing
thing that
that an
an import
import means
means and
and it
it is
is not
not a question
question
that
that
that anything
anything
anything is
isis imported
imported
imported into
into
into the
the
the program,
program,
program, but
but
but only
only
only that
that
that the
the
the class
class
class Random
Random
Random isisis directly
directly
directly
that
that anything
anything is
is imported
imported into
into the
the program,
program, but
but only
only that
that the
the class
class Random
Random is
is directly
directly
available.
available.
available. When
When
When programs
programs
programs and
and
and classes
classes
classes usually
usually
usually uses
uses
uses many
many
many classes
classes
classes from
from
from the
the
the Java
Java
Java API,
API,
API, itit
it can
can
can
available.
available. When
When programs
programs and
and classes
classes usually
usually uses
uses many
many classes
classes from
from the
the Java
Java API,
API, it
it can
can
lead
lead
leadtoto
to many
many
many import
import
import statements,
statements,
statements, and
and
and therefore
therefore
thereforeitit
itisis
is allowed
allowed
allowed to
to
to write
write
write
lead to many import statements, and therefore it is
lead to many import statements, and therefore it is allowed to writeallowed to write
import
import java.util.*;
java.util.*;
import
import java.util.*;
java.util.*;

which
which
which shortly
shortly
shortly means
means
means that
that
that you
you
you can
can
can directly
directly
directly use
useallall
use allthethe classes
theclasses and
classesand interfaces
interfacesinin
andinterfaces the
inthe package
thepackage
package
which
which shortly
shortly means
means that
that you
you can
can directly
directly use
use all
all the
the classes
classes and
and interfaces
interfaces in
in the
the package
package
java.util.
java.util.
java.util. It’s
It’s
It’s something
something
something that
that
thatisis
is many
many
many opinions
opinions
opinions and
and
and arguments
arguments
arguments for
for
for and
and
and against,
against,
against, but
but
butI I
II usually
usually
usually
java.util.
java.util. It’s
It’s something
something that
that is
is many
many opinions
opinions and
and arguments
arguments for
for and
and against,
against, but
but I usually
usually
use
use
use the
the
the short
short
short notation.
notation.
notation.
use the short notation.
use the short notation.
When
When
When you
you
youinin
ina aaNetBeans
NetBeansproject
project creates
creates a aanew
newclass,
class,ititisis automatically
automatically placed
placed inina aapackage
package
When
When you
you in
in aa NetBeans
NetBeans
NetBeans
project
project
project
creates
creates
creates aa new
new
new
class,
class,
class,
it
it
it
is
is
is
automatically
automatically
automatically
placed
placed
placed
in
in
in aa package
package
package
with
with
witha a package
package
aa package statement
statement
statement as
as
as the
the
the first
first
first statement:
statement:
statement:
with package statement as the first statement:
with a package statement as the first statement:
package
package projectname;
projectname;
package
package projectname;
projectname;

Download free eBooks at bookboon.com


164
164
164
164
164
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Packages
paCkages

The
The package
package name
name isis by
by default
default thethe project
project name,
name, but
but itit need
need not
not be
be the
the case.
case. AA package
package
statement
statement must be the first statement in a source file (except for a possible comment), and
must be the first statement in a source file (except for a possible comment), and
the file must contains import statements as the next statements. A Java source
the file must contains import statements as the next statements. A Java source file generally file generally
contains
contains only
only one
one type
type and
and cancan contain
contain only
only one
one public
public type,
type, which
which must
must have
have the
the same
same
name
name as as the
the source
source file.
file. If,
If, for
for example
example you
you have
have the
the type
type

public class Str


{

the source
the source file
file must
must bebe called
called Str.java
Str.java and
and written
written with
with uppercase
uppercase and
and lowercase
lowercase letters
letters as
as
shown here.
shown here. The
The file
file can
can contain
contain several
several types,
types, but
but itit isis generally
generally advised
advised not
not to
to do
do so,
so,
although there
although there are
are sensible
sensible exceptions.
exceptions. When
When aa file
file has
has several
several types,
types, they
they can
can not
not be
be public,
public,
and therefore
and therefore has
has package
package visability.
visability.

Until this
Until this place,
place, my
my projects
projects has
has only
only had
had one
one package,
package, but
but ifif you
you write
write aa large
large program
program
with many
with many classes,
classes, II often
often choses
choses to
to place
place classes
classes into
into multiple
multiple packages,
packages, so
so that
that classes
classes on
on
the same
the same concept
concept are
are inin the
the same
same package.
package.

Download free eBooks at bookboon.com


165
165
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Final example

12 FINAL EXAMPLE
In this chapter I will show the development of a simple GUI program. It’s not a large
program, and the goal is both to show the use of some of the concepts discussed in this
book and to finish with an example where the focus again is on the process.

The process is described in relative detail, and the program is developed according to the
MVC pattern. This pattern and in general the guidelines regarding the development of a
program is first treated in the book Java 7, but you should easily be able to follow the process
without having read Java 7. If in the description of the process is referred to concepts that
you are not quite with on, just ignore it.

12.1 THE TASK


The task is to write a program that simulates a simple game, which consists of a square of
5 × 5 pieces arranged in random order. One of the pieces is empty, and you can move a
piece by moving a neighbor to the empty piece. In the case below (the square on the left)
you can then move the pieces H, E, L and J (you can not move diagonally). The game is
solved when the pieces are arranged as shown in the example to the right.

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com


Click on the ad to read more
166
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Final example

You must assign a high score list to the program where to save the three best results. A
result consists of the number of moves, used to solve the square, and it is therefore to solve
the square by moving as few pieces as possible.

The square is basically a 5 × 5 square, but it must be possible to configure the program so
that you can also play with a 3 × 3 square, a 7 × 7 square and a 9 × 9 square.

PROJECT START

I created a folder called puzzles, and it will contain all the files concerning this project.
I have also created a subfolder called doc, which will contain all the project’s documents.
Preliminary contains this folder the above description of the task.

12.2 ANALYSIS
In this case, the analysis is simple, since the task is simple, and since the formulation of
the task extensively describes the task. There are few issues to be clarified.

In the project description, the individual pieces are symbolized with letters. It’s ok by a 5 × 5
square, but is not sufficient by respectively a 7 × 7 and 9 × 9 square. It is therefore decided
to symbolize the pieces in a 3 × 3 and 5 × 5 square with letters, while there in a 7 × 7 and
9 × 9 must be used integers from 1 onwards.

With regard of the high score list it should be attached a high score list for each of the
four levels of difficulty, as it does not make sense of comparing results from different levels
of difficulty.

As the program’s philosophy is entertainment and results can not be regarded as significant,
it is agreed that high score lists are saved as regular files, and the program does not require
database access. This means that anybody can delete the high score lists.

Download free eBooks at bookboon.com


167
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Final example

The program’s idea is comparable with other entertainment programs like solitaire programs,
which also is associated with a kind of high score list. It is therefore decided that the high
score list should be developed general in order to be used in other applications. A high
score will consist of

-- a name (the user who has obtained the score)


-- a score, that is an integer
-- a time which indicates when the high score is achieved

Moreover, one must be able to specify an ordering that indicates where large values of the
score is positive or negative. A high score list must have room for a certain number of high
scores, as should be defined when the list is created.

REQUIREMENTS SPECIFICATION

The program should basically have the following functions:

1. Play where the user has an interaction with the program and rearrange the pieces
until the square is resolved, or the user giving up.
2. New game where the user selects a new game. This means that the pieces are shuffled
and the state of the program is set to start.
3. Update high score list, a feature which is triggered by the program when the square
is resolved and the user’s point indicates that the user should be on the list. The
user must then enter an identification in the form of the name or an other text.
4. Show high score list, where the user chooses to view the high score list.
5. Choosing the difficulty level where the user must select a square size. This will
automatically result in a new game.

Regarding the high score list there are the following requirements:

1. The high Score list shoould show the top three and thus the players who have
solved the square by moving as few pieces as possible.
2. Each high score must consists of a name, a date and time and the number of pieces
that are moved.
3. It should not be possible (from the program) to delete the high score list.

Download free eBooks at bookboon.com


168
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Final example

The program’s user interface shall consist of three windows:

1. The main window that appears when the application opens. The window displays
25 buttons corresponding to the puzzles pieces, a menu for selecting the above
functions, and a status bar at the bottom of the window, showing how many pieces
are moved.
2. A window that opens, if a player should be on the high score list (if there are not
three players on the list, or the player’s score is better than the last one on the list).
The player should only be able to enter his name.
3. A window that shows the high score list.

In order to illustrate the user interface, a prototype has been developed called Puzzles0. It
shows a design of the main window, and is designed as a grid consisting of 25 buttons.
Furthermore, there is a menu for program’s functions and a status bar to indicate how many
pieces are moved. The prototype has no function, and nothing happens if you click on the
pieces or select a menu item.

Download free eBooks at bookboon.com


Click on the ad to read more
169
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Final example

12.3 DESIGN
The following is both a description of the process, and hence how I have completed the
design of the program Puzzles and partly it is a documentation of the program’s user
interface and classes.

ARCHITECTURE

The starting point for the program’s architecture is the MVC pattern, and to this is defined
the following packages (se below), where:

-- puzzles that only contains the main-class


-- puzzles.ctrls is for the controller classes
-- puzzles.dal is the data access layer, that in this case should be used to classes for
the high score list
-- puzzles.models is for the model classes
-- puzzles.tools is for helper classes
-- brikker.views is for view classes and then the program’s user interface

Download free eBooks at bookboon.com


170
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Final example

THE USER INTERFACE

The prototype from the analysis defines the most concerning the user interface and the main
window is not changed in relation to it and belongs to the package puzzles.views. There are
added two other windows respectively to show the high score list and for entering the name
of a new high score. Are these windows opend from the main program, the results are:

In the same manner as the prototype there is not attached functions to this windows,
and they should only show the user interface. They may thus be seen as an extension of
the prototype.

To create these windows is added a class GUI to the package puzzles.tools containing static
methods to create the user interface. These are examples of methods that could usefully be
moved to a jar file with a class library, and maybe these tools when programming should
be replaced with tools in the class library PaLib.

CLASSES

There is defined a single model class named MainModel. This class represents the game
and keep track of its state. The class will also include the program logic and in accordance
with the general guidelines for the architecture the class represents both the model and the
controller for the main window.

Download free eBooks at bookboon.com


171
JAVA
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION
COLLECTION CLASSES
CLASSES Final
FInal example
example

There is one algorithm, which is not obvious. One can not simply shuffle the pieces randomly
(using a random number generator) and if done, the square could not necessarily be solved.
It is therefore necessary with a strategy (an algorithm) to shuffle the pieces. The idea is to
start with a square that is solved, and then simulate random moves one of the pieces that
can be moved (there are 2, 3 or 4 options). Repeats it many times, and you get a square
where the pieces that are shuffled. The algorithm can be described as follows:

private void shuffle()


{
// start with an ordered square
// (r,c) refers to the blank piece – which to start is the last

// loop over the desired number of substitutions (eg. 1000 or more)


{
// makes random one of the following operations
{
// go, if possible, a step up
// go, if possible, a step down
// go, if possible, a step to the left
// go, if possible, a step to the right
}

Download free eBooks at bookboon.com


Click on the ad to read more
172
172
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
JAVA
AND 4:JAVA’S
4: JAVA’STYPE
TYPE SYSTEM
SYSTEM
CLASSES Final example
ANDCOLLECTION
AND COLLECTIONCLASSES
CLASSES FInalexample
FInal example

// if
// if you
you have
have reached
reached aa new
new position,
position, swapped
swapped this
this piece
piece of
of the
the blanks
blanks
// and
// and to
to start
start the
the next
next iteration
iteration based
based on
on the
the new
new position
position of
of the
the blank
blank
}}
}}

The
The high
high Score
Score list
list isis defined
defined by
by two
two classes
classes defined
defined in
in the
the package
package puzzles.dal:
puzzles.dal:

To solve
To solve the
the problem
problem with
with the
the ordering
ordering of
of the
the high
high score
score objects
objects the
the class
class Highscore
Highscore isis
defined
defined abstract
abstract and
and programs
programs that
that use
use the
the high
high score
score list,
list, therefore
therefore must
must define
define aa derived
derived
class
class that
that implements
implements compareTo(Highscore
compareTo(Highscore hs).
hs). The
The two
two classes
classes are
are shown
shown below,
below, where
where the
the
comments are
comments are removed:
removed:

package puzzles.dal;
package puzzles.dal;

import java.util.*;
import java.util.*;
import java.io.*;
import java.io.*;
public abstract class
public abstract class Highscore
Highscore implements
implements
Comparable<Highscore>, Serializable
Comparable<Highscore>, Serializable
{{
private String
private String name;
name; //
// the
the name
name of
of the
the person
person who
who has
has achieved
achieved this
this score
score
private int score; // the current
private int score; // the current score score
private Calendar
private Calendar time;
time; //// when
when this
this score
score is
is obtained
obtained

public Highscore(String
public Highscore(String name,
name, int
int score)
score)
{{
this.name == name;
this.name name;
this.score == score;
this.score score;
time == Calendar.getInstance();
time Calendar.getInstance();
}}
}}

package puzzles.dal;
package puzzles.dal;

import java.util.*;
import java.util.*;
import java.io.*;
import java.io.*;

public class
public class HighscoreList
HighscoreList implements
implements Iterable<Highscore>,
Iterable<Highscore>, Serializable
Serializable
{{
private List<Highscore>
private List<Highscore> list
list == new
new ArrayList();
ArrayList();
private int
private int size;
size;

Download free eBooks at bookboon.com


173
173
173
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4:
4: JAVA’S
JAVA’S TYPE
JAVA COLLECTION SYSTEM
CLASSES
TYPE SYSTEM Final example
AND COLLECTION CLASSES FInal example
AND COLLECTION
AND COLLECTION CLASSES
CLASSES FInal
FInal example
example

public
public HighscoreList(int size)
public HighscoreList(int
HighscoreList(int size)
size)
{
{
{
this.size
this.size = size;
this.size =
= size;
size;
}
}
}

public
public boolean
boolean addToList(int
addToList(int score)
score)
public boolean addToList(int score)
{
{
{
throw
throw new
new UnsupportedOperationException();
UnsupportedOperationException();
throw new UnsupportedOperationException();
}
}
}

public
public boolean
boolean add(String name, int score)
public boolean add(String
add(String name,
name, int
int score)
score)
{
{
{
throw
throw new
new UnsupportedOperationException();
throw new UnsupportedOperationException();
UnsupportedOperationException();
}
}
}

public
public Iterator<Highscore> iterator()
public Iterator<Highscore>
Iterator<Highscore> iterator()
iterator()
{
{
{
return
return list.iterator();
return list.iterator();
list.iterator();
}
}
}
}
}
}
The high score list has to be saved by ordinary object serialization. It provides a problem in
The
The high
high score
score list
list has
has to be
be saved
toshould
saved by
by ordinary
ordinary object
object serialization.
serialization. It
It provides
provides aa problem
problem in
in
The
termshigh score
of where list
the has
filesto be saved
be by ordinary
saved. It hasobject serialization.
been decided It
that the provides a problem
files should in
be saved
terms
terms of
of where the files should be saved. It has been decided that the files should be saved
terms
in of where
where
a folder underthe files
files should
should be
be saved.
the/var/local/srv/data whereIt
saved. has
Itthis been
been decided
hasfolder decided
must existthat the
thatwith files
files should
the write access. be
should be saved
saved
in
in a
a folder
folder under
under /var/local/srv/data
/var/local/srv/data where
where this
this folder
folder must
must exist
exist with
with write
write access.
access.
in a folder under /var/local/srv/data where this folder must exist with write access.
12.4 PROGRAMMING
12.4
12.4 PROGRAMMING
PROGRAMMING
12.4 PROGRAMMING
The programming includes writing the code for the application itself (see below). It has
The
The programming includes writing the code for the application itself (see below). It has
The programming
been decided not toincludes
programming use thewriting
includes writing the
the code
class library code
PaLibfor the
forand application
the keep the classitself
application GUI(see
itself (see below).
below).
with methodsIt
It has
has
to
been
been decided
decided not
not to
to use
use the
the class
class library
library PaLib
PaLib and
and keep
keep the
the class
class GUI
GUI with
with methods
methods to
to
been decided not to use the class library PaLib and keep the class GUI with methods
the user interface. Similarly, it is left to the class HighscoreList to serialize and deserialie the to
the
the user interface. Similarly, it is left to the class HighscoreList to serialize and deserialie the
the user interface.
user The
objects. finall Similarly,
interface. Similarly, it
it is
is left
classes (types) left
are asto the
the class
class HighscoreList
to follows: HighscoreList to
to serialize
serialize and
and deserialie
deserialie the
the
objects.
objects. The
The finall
finall classes
classes (types)
(types) are
are as
as follows:
follows:
objects. The finall classes (types) are as follows:
puzzles.tools
puzzles.tools
puzzles.tools
- GUI, which is
is aaa class
class with static helper methods to design of the user interface.
--- GUI,
GUI, which
which is class with
with static
static helper
helper methods
methods to
to design
design of
of the
the user
user interface.
interface.

puzzles.views
puzzles.views
puzzles.views
-- MainWindow,
MainWindow, that
that represents
represents the
the main
main window
window and
and concerning
concerning layout
layout it
it is
is essentially
essentially
--- MainWindow, that
MainWindow,
unchanged
that represents
from
represents the
the prototype
the main
main window
of
window and
the
and concerning
analysis.
concerning layout
The class is
layout it
it is
expanded
is essentially
essentially
with the
unchanged
unchanged fromfrom the
from the prototype
the prototype
prototype of of the
of the analysis.
the analysis. The
analysis. The class
The class is
class is expanded
is expanded
expanded with with the
with the
the
unchanged
necessary event handling.
necessary event
necessary event handling.
handling.
-- necessary
Options, event defines
which handling.constants for the user interface. In this case, it are only fonts.
Options, which defines constants for the user interface. In this case, it are only fonts.
---- Options, which
Options, which defines
ScoreDialog,
defines constants
that is a
constants for
dialog box
for the
for
the user
user interface.
entering
interface. In
the name
In this
of
this case,
a
case, it
player
it are
to
are only
be
only fonts.
on the
fonts.
high
- ScoreDialog, that is a dialog box for entering the name of a player to be on the high
--- ScoreDialog, that
ScoreDialog,
score list. The
that is
is aa dialog
window
dialog box
has
box for
the
for entering
same
entering the
look as
the name
name of
shown in
of aa player
the
player to
design,
to be
be on
but
on the
the
the high
high
code is
score list.
score list. The
list. The window
The window
window has has the
has the same
the same look
same look as
look as shown
as shown
shown inin the
in the design,
the design, but
design, but the
but the code
the code
code isis
is
score
changed to ensure a more stable layout.
changed
changed to to ensure
ensure aaa more
to ensure more stable
more stable layout.
stable layout.
layout.
changed

Download free eBooks at bookboon.com


174
174
174
174
JAVA
JAVA 4: JAVA’S TYPE SYSTEM
JAVA 4:
4: JAVA’S
JAVA’S TYPE
TYPE SYSTEM
SYSTEM
AND
AND COLLECTION CLASSES Final example
AND COLLECTION CLASSES
COLLECTION FInal
CLASSES FInal example
example

-- ScoresDialog, there is a dialog box that shows the high score list. The window has
- ScoresDialog, there is a dialog box that shows the high score list. The window has
the same look as shown in the design, but the code is changed to ensure a more
the same look as shown in the design, but the code is changed to ensure a more
stable layout.
stable layout.

puzzles.ctrls
puzzles.ctrls
--- MainController,
MainController, which
which isis aa controller
controller class
class to
to the
the main
main window.
window. This
This class
class is
is in
in this
this
case trivial
case trivial and
and is
is most
most included
included to
to comply
comply with
with the
the MVC.
MVC.
--- ScoreController,
ScoreController, there
there are
are controller
controller class
class for
for ScoreDialog.
ScoreDialog. TheThe class’s
class’s constructor
constructor
validates whether
validates whether aa user
user should
should be
be on
on the
the high
high score
score list
list and
and if
if so
so opens
opens aa ScoreDialog.
ScoreDialog.
--- ScoresController,
ScoresController, that
that is
is controller
controller class
class to
to ScoresDialog.
ScoresDialog.

puzzles.models
puzzles.models
-- MainModel,
MainModel, that
that is
is the
the model
model for
for MainWindow.
MainWindow. The The class
class also
also implements
implements the the
-- MainModel, that is the model for MainWindow. The class also implements the
logic of the game.
logic of the game.
logic of the game.
-- PuzzlesScore,
PuzzlesScore, that
that is
is extended
extended from
from Highscore
Highscore and
and is
is aa concrete
concrete Highscore
Highscore class.
class.
-- PuzzlesScore, that is extended from Highscore and is a concrete Highscore class.
-- MoveListener,
MoveListener, that is an interface, that defines an observer for changes in the
that is an interface, that defines an observer for changes in the state
state
-- MoveListener, that is an interface, that defines an observer for changes in the state
of
of the
the model.
model.
of the model.
-- SolveListener,
SolveListener, that
that is
is an
an interface,
interface, that
that defines
defines an
an observer
observer for
for solving
solving the
the square.
square.
-- SolveListener, that is an interface, that defines an observer for solving the square.

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57


Download free eBooks at bookboon.com
Click on the ad to read more
175
175
175
JAVA 4: JAVA’S TYPE SYSTEM
JAVACOLLECTION
AND 4: JAVA’S TYPE SYSTEM
CLASSES Final example
AND COLLECTION CLASSES FInal example

puzzles.dal
--- Highscore,
Highscore,that
thatisisan
anabstract
abstractclass,
class,that
thatrepresents
representsaahigh
highscore.
score.The
Theclass
classisisabstract,
abstract,
because itit defines
because defines but
but not
not implements
implements thethe interfacet
interfacet Comparable<Highscore>.
Comparable<Highscore>.
--- HighscoreList,
HighscoreList, that
that defines
defines aa high
high score
score list
list and
and serialize
serialize and
and deserialize
deserialize Highscore
Highscore
objects.
objects.

To test
To test that
that the
the program
program works,
works, the
the folowing
folowing must
must be
be validated:
validated:

--- isis the


the model
model created
created correct
correct and
and are are the
the pices
pices shuffled
shuffled sensibly
sensibly
--- are the
are the pieces
pieces moved
moved correctly
correctly
--- can the
can the square
square bebe solved
solved andand areare the the players
players added
added toto the
the high
high score
score lists
lists in
in the
the
right order
right order
--- works the
works the function
function NewNew game
game
--- isis itit possible
possible to
to select
select aa new
new difficulty
difficulty levellevel
--- can the
can the high
high score
score lists
lists be
be shown
shown
--- shows About
shows About Puzzles
Puzzles the
the correct
correct window
window
--- isis the
the program’s
program’s look
look and
and feel
feel atat itit should
should be
be

The first
The first point
point isis best
best solved
solved by
by playing
playing the
the game.
game.

Download free eBooks at bookboon.com


176
176
JAVA 4: JAVA’S TYPE SYSTEM
AND COLLECTION CLASSES Final example

The next points can only be tested by using the program and thus play the game. It is
relatively simple to test the 3 × 3 to 5 × 5 squares, but the 7 × 7 or 9 × 9, it is more difficult
since it takes a long time to solve the square. You can solve this problem by changing the
loop in the method shuffle() so that it only takes one or a few exchanges.

The last point can only be tested in collaboration with the user and get his agreement that
the user interface is satisfactory.

12.5 TEST
When a program is finished, it must be tested in real environments and any of other than
the programmer. In this case there is not much to do in the finally test, because the program
does not have to communicate with other programs, but the program must of course be
tested, and it must be in correct user environment.

In this case, you can create a folder somewhere on your hard drive and then copy the
program’s jar file to that folder and start the program from a prompt. Then there is not
much else to do than to play and try to solve the squares. Here you must pay particular
attention to the high score list, and the players are correctly added to the lists. In addition,
you must have an eye on the visual, and if all looks as it should do. Specifically, you can
use the following test cases:

1. Set the level to a et 3 × 3 square


2. Solve the square and add the user to the high score list
3. Solve the square again, but this time with many swap, such that the user get a
high score with many moves
4. Solve the square a third time
5. Show the high score list and examine whether the three players are correctly inserted
6. Solve squares until another player is added to the high score list
7. Display the high score list to ensure that the last player is properly inserted
8. Repeat the above with a 5 × 5 square
9. Manually delete the two files to high score lists
10. Display the high score lists for both a 3 × 3 and 5 × 5 square and ensure that they
are empty

If these test cases are performed satisfactorily, I will consider the program as tested and
ready to use.

Download free eBooks at bookboon.com


177
JAVA
JAVA4:4:JAVA’S
JAVA’STYPE
TYPESYSTEM
SYSTEM
AND
ANDCOLLECTION
COLLECTIONCLASSES
CLASSES Final
FInalexample
example

12.6
12.6 THE
THELAST
LASTSTEP
STEP
As
Asthe
thelast
lastpart
partofofthe
thetask
taskthat
thatmust
mustbe
bewritten
writtenaascript
scriptthat
thatcan
caninstall
installthe
thesoftware
softwareon
onaa
computer.
computer.AsAsthe
thefirst
firstI’ve
I’vedrawn
drawnananicon
iconfor
forthe
theprogram
program

that
thatI Ihave
havecalled
calledpuzzles.png.
puzzles.png.Then
ThenI Ihave
havecreated
createdaadirectory
directorynamed
namedpuzzles
puzzlesthat
thatcontains
contains
the
theprogram’s
program’sjarjarfile
fileand
andthe
theabove
aboveicon
iconand
andthe
thefollowing
followingscript.
script.To
Toinstall
installthe
theprogram
program
you
you must then make the directory puzzles to the current directory and execute the scriptasas
must then make the directory puzzles to the current directory and execute the script

sudo ./puzzles.sh

This
Thiswill
willcreate
createthe
thenecessary
necessarydirectories
directoriesand
andthetheprogram
programisiscopied
copiedtoto/usr/local/games
/usr/local/gamesand
and
you
youget
getananicon
iconononthe
thedesktop
desktopthat
thatrefers
referstotothe
theprogram.
program.The
Thescript
scriptisisasasfollows:
follows:

#!/bin/bash
DIR=$(pwd)
cd /var/local
if [ -d srv ]
then
cd srv
if [ -d data ]
then
cd data
else
mkdir data
fi
else
mkdir srv
cd srv
mkdir data
cd data
fi
if [ -d highscores ]
then
rm highscores/* 2> /dev/null
else
mkdir highscores
fi
cd "$DIR"
cp Puzzles.jar /usr/local/games

Download free eBooks at bookboon.com


178
178
JAVA 4: JAVA’S TYPE SYSTEM
JAVA
AND 4: JAVA’S TYPE
COLLECTION SYSTEM
CLASSES Final example
AND COLLECTION CLASSES FInal example

cp puzzles.png /usr/local/games
cd /usr/local/bin
echo 'java -jar /usr/local/games/Puzzles.jar' > puzzle
chmod 755 puzzle
cd /usr/share/applications
echo '[Desktop Entry]' > puzzles.desktop
echo 'Name=Puzzles' >> puzzles.desktop
echo 'Exec=puzzle' >> puzzles.desktop
echo 'Icon=/usr/local/games/puzzles.png' >> puzzles.desktop
echo 'Type=Application' >> puzzles.desktop
echo 'Categories=Games' >> puzzles.desktop
echo 'Encoding=UTF-8' >> puzzles.desktop

ItItisisaarelatively
relativelysimple
simplescript,
script,but
butshort
shortthe
thefollowing
followingtakes
takesplace
placeononthe
thecondition
conditionthat
thatthe
the
current directory is the directory with the script, and the jar file and the
current directory is the directory with the script, and the jar file and the icon: icon:

1.1.the
thename
nameofofthe thedirectory
directoryisisstored
storedininaavariable
variablenamed
namedDIR DIR
2.2.the
thecurrent
currentdirectory
directoryisischanged
changedtoto/var/local
/var/local
3.3.here
here is created a subdirectory srv, ifititdoes
is created a subdirectory srv, if doesnotnotalready
alreadyexist,
exist,and
andhere
hereagain
againaa
subdirectory
subdirectorydata data
4.4.ififdata
datahashasaasubdirectory
subdirectoryhighscores
highscoresdelete
deleteall
allfiles
filesininthis
thisdirectory,
directory,and
andotherwise
otherwise
create
createaasubdirectory
subdirectoryhighscores
highscores
5.5.the
the current directory ischange
current directory is changetotothe thedirectory
directorystored
storedininDIR DIR
6.6.the
thejar
jarfile
fileand
andthetheicon
iconarearecopied
copiedtoto/usr/local/games
/usr/local/games
7.7.current
currentdirectory
directoryisischanged
changedtoto/usr/local/bin
/usr/local/bin
8.8.here
hereisiscreated
createdaasimple
simplescript
script(only(onlyone
oneline)
line)containing
containingthe thestart
startcommand
command
9.9.for this script the rights is set so that everyone has read
for this script the rights is set so that everyone has read og execute og execute
10.
10.thethecurrent
currentdirectory
directoryisischanged
changedtoto/usr/share/applications
/usr/share/applications
11.
11.here
herethethescript
scriptcreates
createsaafilefilenamed
namedpuzzles.desktop,
puzzles.desktop,and andit’s
it’sthe
thecommands
commandsininthat
that
file
filethat
thatcreates
createsan anicon
iconforforthetheprogram
program

Download free eBooks at bookboon.com


179
179

You might also like