Copy of Slides - hrm-kt

advertisement
Exception Handling
& Java Utility API
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Course Objective
• Exception Handling
• Java Utilities classes
• Java Collection Framework
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Learning Approach

The following are strongly suggested for a
better learning and understanding of this
course:
 Noting down the key concepts in the class
 Analyze all the examples / code snippets provided
 Study and understand the self study topics
 Completion and submission of all the assignments, on time
 Completion of the self review questions in the lab guide
 Study and understand all the artifacts including the reference
materials / e-learning / supplementary materials specified
 Completion of the project (if application for this course) on time
inclusive of individual and group activities
 Taking part in the self assessment activities
 Participation in the doubt clearing sessions
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Session 1
EXCEPTION HANDLING
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Java Exception - Introduction
• Exception is shorthand for the phrase “exceptional event“.
• An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's
instructions.
• When an error occurs within a method, the method creates an
object and hands it off to the runtime system. The object, called
an exception object, contains information about the error,
including its type and the state of the program when the error
occurred.
• Creating an exception object and handing it to the runtime
system is called throwing an exception.
• It is essential that a programmer foresees these conditions and
takes care of them by writing proper error messages to be
flashed when the program encounters an error.
• Error and exception handling is used to foresee and identify
error conditions and perform processing to take care of their
impact.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Call stack

After a method throws an
exception, the runtime system
attempts to find something to
handle it. The set of possible
"somethings" to handle the
exception is the ordered list of
methods that had been called
to get to the method where the
error occurred. The list of
methods is known as the call
stack
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Call stack (cont)



The runtime system searches the
call stack for a method that contains
a block of code that can handle the
exception. This block of code is
called an exception handler.
The exception handler chosen is
said to catch the exception.
If the runtime system exhaustively
searches all the methods on the call
stack without finding an appropriate
exception handler, as shown in the
next figure, the runtime system
(and, consequently, the program)
terminates.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Three Kinds of Exceptions



The first kind of exception is the checked exception. These
are exceptional conditions that a well-written application
should anticipate and recover from. All exceptions are
checked exceptions, except for those indicated
by Error, RuntimeException, and their subclasses.
The second kind of exception is the error. These are
exceptional conditions that are external to the application,
and that the application usually cannot anticipate or
recover from.
The third kind of exception is the runtime exception. These
are exceptional conditions that are internal to the
application, and that the application usually cannot
anticipate or recover from. These usually indicate
programming bugs, such as logic errors or improper use of
an API.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Throwable Class and Its Subclasses
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Error Class
When a dynamic linking failure or other hard
failure in the Java virtual machine occurs, the
virtual machine throws an Error.
 Simple programs typically do not catch or
throw Errors.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Exception Class
Most programs throw and catch objects that
derive from the Exception class.
 An Exception indicates that a problem
occurred, but it is not a serious system
problem.
 Most programs you write will throw and
catch Exceptions.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The Catch or Specify Requirement

Valid Java programming language code must honor
the Catch or Specify Requirement. This means that
code that might throw certain exceptions must be
enclosed by either of the following:
 A try statement that catches the exception. The try must
provide a handler for the exception.
 A method that specifies that it can throw the exception.
The method must provide a throws clause that lists the
exception

Code that fails to honor the Catch or Specify
Requirement will not compile.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Example
1.
2.
3.
4.
5.
6.
7.
//Note: This class won't compile by design!
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers {
private List<Integer> list;
private static final int SIZE = 10;
public ListOfNumbers () {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}
8.
9.
10.
11.
12.
13.
public void writeList() {
PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
14.
15.
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
out.close();
16.
17.
18.
19.
}
20.
21.
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Example (cont)



Line 15 call a constructor to initializes an output stream on
a file. If the file cannot be opened, the constructor throws
an IOException.
Line 17 call to the ArrayList class's getmethod, which will
throws an IndexOutOfBoundsException if the value of
its argument is too small (less than 0) or more than the
number of elements currently contained by the ArrayList.
If you try to compile this code, the compiler prints an error
message about the exception thrown by line 15. However,
it does not display an error message about the exception
thrown by line 17. The reason is that the exception thrown
by the constructor, IOException, is a checked exception,
and the one thrown by the get method,
IndexOutOfBoundsException, is an unchecked
exception.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The try block
The first step in constructing an exception
handler is to enclose the code that might
throw an exception within a try block.
 You can put each line of code that might
throw an exception within its own try block
and provide separate exception handlers for
each.
 Or, you can put all the code within a single
try block and associate multiple handlers
with it.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The try block
try {
System.out.println("Entered try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
}
catch and finally statements . . .

If an exception occurs within the try block, that
exception is handled by an exception handler
associated with it. To associate an exception
handler with a try block, you must put
a catch block after it
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The catch Blocks

You associate exception handlers with a try block
by providing one or more catch blocks directly
after the try block:
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}

Each catch block is an exception handler and
handles the type of exception indicated by its
argument. The argument type, ExceptionType,
declares the type of exception that the handler can
handle and must be a class that inherits from
the Throwable class.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The catch Blocks

The catch block contains code that is executed if
and when the exception handler is invoked. The
runtime system invokes the exception handler
when the handler is the first one in the call stack
whose ExceptionType matches the type of the
exception thrown.
try {
...
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
throw new SampleException(e);
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The catch Blocks


Both handlers print an error message. The second
handler does nothing else. By catching any
IOException that's not caught by the first
handler, it allows the program to continue
executing.
The first handler, in addition to printing a message,
throws a user-defined exception. In this example,
when the FileNotFoundException is caught
it causes a user-defined exception called
SampleException to be thrown. You might
want to do this if you want your program to handle
an exception in this situation in a specific way.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The finally Block



The finally block always executes when the try block
exits. This ensures that the finally block is executed
even if an unexpected exception occurs.
finally is useful for more than just exception handling
— it allows the programmer to avoid having cleanup code
accidentally bypassed by a return, continue, or break.
Putting cleanup code in a finally block is always a good
practice, even when no exceptions are anticipated.
If the JVM exits while the try or catch code is being
executed, then the finally block may not execute.
Likewise, if the thread executing the try or catch code
is interrupted or killed, the finally block may not
execute even though the application as a whole continues.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The finally Block

The try block of the writeList method that you've
been working with here opens a PrintWriter. The
program should close that stream before exiting
the writeList method. This poses a somewhat
complicated problem because writeList's try block
can exit in one of three ways:
 The new FileWriter statement fails and throws an
IOException.
 The list.get(i) statement fails and throws an
ArrayIndexOutOfBoundsException.
 Everything succeeds and the try block exits normally.

The runtime system always executes the statements within
the finally block regardless of what happens within the
try block. So it's the perfect place to perform cleanup.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
The finally Block

The following finally block for the writeList
method cleans up and then closes the PrintWriter.
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}

Important: The finally block is a key tool for
preventing resource leaks. When closing a file or otherwise
recovering resources, place the code in a finally block
to ensure that resource is always recovered.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Putting It All Together
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("ArrayIndexOutOfBoundsException:" + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException:" + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Scenario 1

Scenario 1: An Exception Occurs
 For example, the constructor for the FileWriter throws an
IOException if the program cannot create or write to the file
indicated.
 The runtime system immediately stops executing the try block;
method calls being executed are not completed.
 The runtime system then starts searching at the top of the method call
stack for an appropriate exception handler. In this example, when
the IOException occurs, the FileWriter constructor is at the
top of the call stack.
 However, the FileWriter constructor doesn't have an appropriate
exception handler, so the runtime system checks the next method —
the writeList method — in the method call stack.
The writeList method has two exception handlers: one
for IOException and one for
ArrayIndexOutOfBoundsException.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Scenario 1 (cont)




The runtime system checks writeList's handlers in the
order in which they appear after the try statement.
The argument to the first exception handler is
ArrayIndexOutOfBoundsException, this does not
match the type of exception thrown.
So the runtime system checks the next exception handler
—IOException. This matches the type of exception
that was thrown, so the runtime system ends its search for
an appropriate exception handler.
Now that it has found an appropriate handler, the code in
that catch block is executed.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Scenario 1 (cont)
After the exception handler executes, the
runtime system passes control to the
finally block.
 Code in the finally block executes
regardless of the exception caught above it.
 In this scenario, the FileWriter was never
opened and doesn't need to be closed.
 After the finally block finishes executing,
the program continues with the first
statement after the finally block.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Scenario 1 (cont)

Here's the complete output from the program
when an IOException is thrown:
Entering try statement
Caught IOException: OutFile.txt
PrintWriter not open
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Scenario 2

Scenario 2: The try Block Exits Normally
 In this scenario, all the statements within the scope of
the try block execute successfully and throw no
exceptions.
 Execution falls off the end of the try block, and the
runtime system passes control to the finally block.
 Because everything was successful, the PrintWriter is
open when control reaches the finally block, which
closes the PrintWriter.
 Again, after the finally block finishes executing, the
program continues with the first statement after
the finally block.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Scenario 2 (cont)

Here is the output from the program when no
exceptions are thrown:
Entering try statement
Closing PrintWriter
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Specifying the Exceptions Thrown



The previous section showed how to write an
exception handler for the writeList method in
the ListOfNumber sclass. Sometimes, it's
appropriate for code to catch exceptions that can
occur within it.
In other cases, however, it's better to let a method
further up the call stack handle the exception.
For example, if you were providing a library with
the ListOfNumbers class as part in a package,
you probably couldn't anticipate the needs of all
the users of your library. In this case, it's better
to not catch the exception and to allow a method
further up the call stack to handle it.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Specifying the Exceptions Thrown
If the writeList method doesn't catch the
checked exceptions that can occur within it,
the writeList method must specify that it
can throw these exceptions.
 Let's modify the original writeList
method to specify the exceptions it can throw
instead of catching them.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Specifying the Exceptions Thrown



To specify that writeList can throw two
exceptions, add a throws clause to the method
declaration for the writeList method.
The throws clause comprises the throws keyword
followed by a comma-separated list of all the
exceptions thrown by that method.
The clause goes after the method name and
argument list and before the brace that defines the
scope of the method:
public void writeList() throws IOException, ArrayIndexOutOfBoundsException {
…
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
How to Throw Exceptions




Before you can catch an exception, some code somewhere
must throw one.
Any code can throw an exception: your code, code from a
package written by someone else, the packages that come
with the Java platform, or the Java runtime environment.
Regardless of what throws the exception, it's always
thrown with the throw statement.
The throw statement requires a single argument: a
throwable object. Throwable objects are instances of any
subclass of the Throwable class. Example:
throw someThrowableObject;
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Example
import java.util.EmptyStackException;
public class ThrowAnException {
private List<Integer> list;
public void writeList() {
if (list == null || list.isEmpty()) {
throw new EmptyStackException();
}
try {...
}...
}
public static void main(String[] args) {
ThrowAnException sample = new ThrowAnException();
sample.writeList();
}
}
Output:
Exception in thread "main" java.util.EmptyStackException
at vn.com.fsoft.java.lesson4.ThrowAnException.writeList(ThrowAnException.java:18)
at vn.com.fsoft.java.lesson4.ThrowAnException.main(ThrowAnException.java:42)
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Chained Exceptions
An application often responds to an
exception by throwing another exception. In
effect, the first exception causes the second
exception.
 It can be very helpful to know when one
exception causes another.
 Chained Exceptions help the programmer do
this.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Chained Exceptions

The following example shows how to use a chained
exception:
try { ...
} catch (IOException e) {
throw new SampleException("Other IOException", e);
}

In this example, when an IOException is
caught, a new SampleException exception is
created with the original cause attached and the
chain of exceptions is thrown up to the next higher
level exception handler.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Stack Trace
A stack trace provides information on the
execution history of the current thread and
lists the names of the classes and methods
that were called at the point when the
exception occurred.
 A stack trace is a useful debugging tool that
you'll normally take advantage of when an
exception has been thrown.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Accessing Stack Trace Information


Now let's suppose that the higher-level exception handler wants to
dump the stack trace in its own format.
The following code shows how to call the getStackTrace method on
the exception object:
catch (Exception cause) {
StackTraceElement elements[] = cause.getStackTrace();
for (int i = 0; i < elements.length; i++) {
System.err.println(
elements[i].getFileName() + ":"
+ elements[i].getLineNumber()
+ ">> "
+ elements[i].getMethodName() + "()“
);
}
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Creating Exception Classes


When faced with choosing the type of exception to
throw, you can either use one written by someone
else, or you can write one of your own.
You should write your own exception classes if you
answer yes to any of the following questions:
 Do you need an exception type that isn't represented by
those in the Java platform?
 Do you need more specific information about exception?
 Would it help users if they could differentiate your
exceptions from those thrown by classes written by other
vendors?
 Does your code throw more than one related exception?
 Should your package be independent and self-contained?
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Example

For example, your application has a module in
business logic layer to search and create
Customer. You may have some method:
 searchCustomer(Long customerID)
 searchCustomer(String customerName)
 createCustomer(Long customerID, String customerName)

You want that, when the presentation layer
call to this module, it may know what
happens if these method could not found or
create a Customer, and also know exactly
which Customer is it working with.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Example (cont)


This figure illustrates one possible class hierarchy for the exceptions
thrown by this module. You may have another solution.
For readable code, it's good practice to append the string Exception
to the names of all classes that inherit (directly or indirectly) from
the Exception class.
Exception
BusinessLogicException
CustomerException
CustomerNotFoundException
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
DuplicatedCustomerException
04e-BM/NS/HDCV/FSOFT v2/3
BusinessLogicException.java
public class BusinessLogicException extends Exception {
public BusinessLogicException() {
super();
}
public BusinessLogicException(String message) {
super(message);
}
public BusinessLogicException(Throwable cause) {
super(cause);
}
public BusinessLogicException(String message, Throwable cause)
{
super(message, cause);
}
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
CustomerException.java
public class CustomerException extends BusinessLogicException {
private
private
private
private
static final String ID = "Customer ID: ";
static final String NAME = "Customer Name: ";
Long customerID;
String customerName;
public CustomerException(Long customerID, String customerName) {
this.customerID = customerID;
this.customerName = customerName;
}
public CustomerException(Long customerID) {
this(customerID, null);
}
public CustomerException(String customerName) {
this(null, customerName);
}
public String getMessage() {
StringBuffer msg = new StringBuffer();
if (customerID != null) {
msg.append(ID).append(customerID);
}
if (customerName != null) {
msg.append(NAME).append(customerName);
}
return msg.toString();
}
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
CustomerNotFoundException.java
public class CustomerNotFoundException extends CustomerException {
private static final String DEFAULT_MSG = "Could not found the
customer in the database.";
public CustomerNotFoundException(Long customerID) {
super(customerID);
}
public CustomerNotFoundException(Long customerID, String customerName)
{
super(customerID, customerName);
}
public CustomerNotFoundException(String customerName) {
super(customerName);
}
public String getMessage() {
StringBuffer msg = new StringBuffer(DEFAULT_MSG);
msg.append(super.getMessage());
return msg.toString();
}
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
DuplicatedCustomerException.java
public class DuplicatedCustomerException extends CustomerException {
private static final String DEFAULT_MSG = "This customer is already
exists.";
public DuplicatedCustomerException(Long customerID, String
customerName) {
super(customerID, customerName);
}
public DuplicatedCustomerException(Long customerID) {
super(customerID);
}
public DuplicatedCustomerException(String customerName) {
super(customerName);
}
public String getMessage() {
StringBuffer msg = new StringBuffer(DEFAULT_MSG);
msg.append(super.getMessage());
return msg.toString();
}
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Some common Runtime Exception

When programming, you may often have to
deal with:
 java.lang.NullPointerException
 java.lang.IndexOutOfBoundsException
 java.lang.ClassCastException

To avoid these exception, you should always:
Check null before use.
Check array is empty, array’s length before use.
Check type before casting.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Advantages of Exceptions
Separating Error-Handling Code from
"Regular" Code
 Propagating Errors Up the Call Stack
 Grouping and Differentiating Error Types

© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Summary


A program can use exceptions to indicate that an error
occurred. To throw an exception, use
the throw statement and provide it with an exception
object — a descendant of Throwable — to provide
information about the specific error that occurred. A
method that throws an uncaught, checked exception must
include a throws clause in its declaration.
A program can catch exceptions by using a combination of
the try, catch, and finally blocks.
 The try block identifies a block of code in which an exception can occur.
 The catch block identifies a block of code, known as an exception handler, that can
handle a particular type of exception.
 The finally block identifies a block of code that is guaranteed to execute, and is the
right place to close files, recover resources, and otherwise clean up after the code
enclosed in the try block.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Summary (cont)


The try statement should contain at least
one catch block or a finally block and may
have multiple catch blocks.
The class of the exception object indicates the type
of exception thrown. The exception object can
contain further information about the error,
including an error message. With exception
chaining, an exception can point to the exception
that caused it, which can in turn point to the
exception that caused it, and so on.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Session 2
UTILITIES CLASSES
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Utilities classes in the java.lang package
• The java.lang package defines classes that are
fundamental to the Java language. For this reason,
all classes in the java.lang package are imported
automatically, so there is no reason to write an
import statement for them.
• The java.lang package contains many of the most
fundamental and often-used classes in the Java API:
o
o
o
Strings: String & String Buffer classes
Math class
Wrappers:








Boolean
Byte
Character
Double
Float
Integer
Long
Short
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
java.lang.String
• Strings Are Immutable Objects
String s = “abc”;
String s2 = s;
s = s.concat(“def”);
• Some important methods:
public
public
public
public
public
public
public
public
public
public
public
char charAt(int index)
String concat(String s)
boolean equals(Object anObject)
boolean equalsIgnoreCase(String s)
int length()
String replace(char old, char new)
String substring(int begin)
String substring(int begin, int end)
String toLowerCase()
String toUpperCase()
String trim()
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
java.lang.StringBuffer
• The StringBuffer class should be used when you have to make
a lot of modifications to strings of characters. As we discussed
in the previous section, String objects are immutable, so if you
choose to do a lot of manipulations with String objects, you
will end up with a lot of abandoned String objects in the String
pool.
• A common use for StringBuffers is file I/O when large, everchanging streams of input are being handled by the program.
In these cases, large blocks of characters are handled as its,
and StringBuffer objects are the ideal way to handle a block of
data, pass it on, and then reuse the same memory to handle
the next block of data.
• Some important methods:
public
public
public
public
synchronized StringBuffer append(String s)
synchronized StringBuffer insert(int offset, String s)
synchronized StringBuffer reverse()
String toString()
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
java.lang.Math
• Math class, which is used to perform basic mathematical
operations.
• All methods of the Math class are defined as static, you
don’t need to create an instance to use them. In fact, it’s
not possible to create an instance of the Math class
because the constructor is private.
• You can’t extend the Math class because it’s marked final
• The Math class defines approximations for the
mathematical constants pi and e. Their signatures are as
follows:
public final static double Math.PI
public final static double Math.E
• Methods: abs(x), ceil(d), floor(d), max(x,
y), min(x, y), random(), round(x), sin(x),
cos(x), tan(x), sqrt(x),…
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Wrappers
• There is a wrapper class for every primitive in Java. For
instance the wrapper class for int is Integer, for float is
Float, and so on. Remember that the primitive name is
simply the lowercase name of the wrapper except for char,
which maps to Character, and int, which maps to Integer.
• The wrapper classes in the Java API serve two primary
purposes:
To provide a mechanism to “wrap” primitive values in an object so
that the primitives can be included in activities reserved for objects,
like as being added to Collections, or returned from a method with
an object return value.
o To provide an assortment of utility functions for primitives. Most of
these functions are related to various conversions: converting
primitives to and from String objects, and converting primitives and
String objects to and from different bases (or radix), such as binary,
octal, and hexadecimal.
o
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Wrappers (cont)

All of the numeric wrapper classes are subclasses of
the abstract class Number:
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Java.lang – Wrappers (cont.)
• Creating Wrapper Objects:
o
The Wrapper Constructors:
Integer i1 = new Integer(42);
Integer i2 = new Integer("42");
o
The valueOf() Methods
Integer i3 = Integer.valueOf("101011", 2);
Float f1 = Float.valueOf("3.14f");
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Java.lang – Wrappers (cont.)
• Using Wrapper Conversion Utilities
xxxValue() => convert the value of a wrapped numeric to a
primitive
o parseXxx() and valueOf() => take a String as an argument,
throw a NumberFormatException if the String argument is
not properly formed, and can convert String objects from different
bases (radix), when the underlying primitive type is any of the four
integer types. The difference between the two methods is
 parseXxx() returns the named primitive.
 valueOf() returns a newly created wrapped object of the type that
invoked the method.
o toString() => returns a String with the value of the primitive
wrapped in the object
o toXxxString() (Binary, Hexadecimal, Octal) => The Integer and
Long wrapper classes let you convert numbers in base 10 to other
bases. These conversion methods, toXxxString(), take an int or
long, and return a String representation of the converted number.
o
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Java.lang – equals() method
• equals() is used only to compare objects.
• equals() returns a boolean, true or false.
• The StringBuffer class has not
overridden equals().
• The String and wrapper classes are final
and have overridden equals().
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Summary




Strings are a sequence of characters and are widely used in
Java programming. In the Java programming language, strings
are objects. The String class has over 60 methods and 13
constructors.
The String class has many methods to find and retrieve
substrings; these can then be easily reassembled into new
strings using the + concatenation operator.
The String class also includes a number of utility methods,
among them split(), toLowerCase(), toUpperCase(), and
valueOf(). The latter method is indispensable in converting user
input strings to numbers. The Number subclasses also have
methods for converting strings to numbers and vice versa.
In addition to the String class, there is also a StringBuilder class.
Working with StringBuilder objects can sometimes be more
efficient than working with strings. The StringBuilder class
offers a few methods that can be useful for strings, among
them reverse().
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Summary (cont)



You use one of the wrapper classes – Byte, Double, Float,
Integer, Long, or Short – to wrap a number of primitive type in
an object. The Java compiler automatically wraps (boxes)
primitives for you when necessary and unboxes them, again
when necessary.
The Number classes include constants and useful class
methods. The MIN_VALUE and MAX_VALUE constants contain
the smallest and largest values that can be contained by an
object of that type. The byteValue, shortValue, and similar
methods convert one numeric type to another.
The valueOf method converts a string to a number, and
thetoString method converts a number to a string.
The Math class contains a variety of class methods for
performing mathematical functions, including exponential,
logarithmic, and trigonometric methods. Math also includes
basic arithmetic functions, such as absolute value and
rounding, and a method, random(), for generating random
numbers.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Session 3
JAVA COLLECTIONS FRAMEWORK
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections
• A collection (sometimes called a container) is
an object that groups multiple elements into
a single unit.
• Collections are used to store, retrieve and
manipulate data, and to transmit data from
one method to another.
• Collections typically represent data items that
form a natural group, a card hand, a mail
folder, a telephone directory…
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections Framework
• The Java collections framework is made up of a
set of interfaces and classes for working with
groups of objects
• The Java Collections Framework provides
Interfaces: abstract data types representing
collections.
o Implementations: concrete implementations of the
collection interfaces.
o Algorithms: methods that
perform useful
computations, like
searching and sorting, on
objects that implement
collection interfaces.
o
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Interface Collection and Class Collections
• Interface Collection
o
o
o
o
A Collection represents a group of objects, known as its
elements
Some Collection implementations allow duplicate elements and
others do not
Some are ordered and others unordered
Contains bulk operations
 Adding, clearing, comparing and retaining objects
o
Collection is used to pass collections around and manipulate
them when maximum generality is desired
• Class Collections
o
o
Provides static methods that manipulate collections
Collections can be manipulated polymorphically
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
More on Collection interface
• All collection implementations (which implement some sub
interface of Collection like Set or List) have a constructor
that takes a Collection argument.
• This constructor allows the caller to create a Collection of a
desired implementation type, initially containing all of the
elements in any given Collection, whatever its subinterface
or implementation type. Suppose you have a Collection, c,
which may be a List, a Set, or some other kind of Collection.
List li = new ArrayList(c);
The statement creates a
new ArrayList (an
implementation of the List
interface), initially
containing all of the
elements in c
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
C may be a List, a Set, or
some other kind of
Collection
04e-BM/NS/HDCV/FSOFT v2/3
More on Collection interface (cont.)
The interface does about what
you'd expect, given that a
Collection represents a group of
objects. It has methods to tell
you how many elements are in
the collection (size, isEmpty), to
check if a given object is in the
collection (contains), to add and
remove an element from the
collection (add, remove), and to
provide an iterator over the
collection (iterator).
The add method is defined generally enough so that it makes sense for
collections that allow duplicates as well as those that don't. It guarantees that the
Collection will contain the specified element after the call completes, and returns
true if the Collection changes as a result of the call. Similarly, the remove method
is defined to remove a single instance of the specified element from the
Collection, assuming the Collection contains the element, and to return true if
the Collection was modified as a result.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections - Lists
• Ordered Collection that can
contain duplicate elements
• Sometimes called a sequence
• Implemented via interface
List
o ArrayList
o LinkedList
o Vector
• List provides a richer
ListIterator
ListIterator allows you to traverse
the list in either direction, modify
the list during iteration, and obtain
the current position of the iterator
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
CollectionTest.java
1 // CollectionTest.java
2 // Using the Collection interface.
3 import java.awt.Color;
4 import java.util.*;
5
6 public class CollectionTest {
7 private static final String colors[] = { "red", "white", "blue" };
8
9 // create ArrayList, add objects to it and manipulate it
10 public CollectionTest()
11 {
12 List list = new ArrayList();
13
14 // add objects to list
15 list.add( Color.MAGENTA ); // add a color object
16
17 for ( int count = 0; count < colors.length; count++ )
18 list.add( colors[ count ] );
19
20 list.add( Color.CYAN ); // add a color object
21
22 // output list contents
23 System.out.println( "\nArrayList: " );
24
25 for ( int count = 0; count < list.size(); count++ )
26 System.out.print( list.get( count ) + " " );
27
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
CollectionTest.java
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// remove all String objects
removeStrings( list );
// output list contents
System.out.println( "\n\nArrayList after calling removeStrings: " );
for ( int count = 0; count < list.size(); count++ )
System.out.print( list.get( count ) + " " );
} // end constructor CollectionTest
// remove String objects from Collection
private void removeStrings( Collection collection )
{
Iterator iterator = collection.iterator(); // get iterator
// loop while collection has items
while ( iterator.hasNext() )
if ( iterator.next() instanceof String )
iterator.remove(); // remove String object
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
CollectionTest.java
51
52
53
54
55
56
public static void main( String args[] )
{
new CollectionTest();
}
} // end class CollectionTest
Output:
ArrayList:
java.awt.Color[r=255,g=0,b=255] red white blue java.awt.Color[r=0,g=255,b=255]
ArrayList after calling removeStrings:
java.awt.Color[r=255,g=0,b=255] java.awt.Color[r=0,g=255,b=255]
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
ListTest.java
1 // ListTest.java
2 // Using LinkLists.
3 import java.util.*;
4
5 public class ListTest {
6 private static final String colors[] = { "black", "yellow",
7 "green", "blue", "violet", "silver" };
8 private static final String colors2[] = { "gold", "white",
9 "brown", "blue", "gray", "silver" };
10
11 // set up and manipulate LinkedList objects
12 public ListTest()
13 {
14 List link = new LinkedList();
15 List link2 = new LinkedList();
16
17 // add elements to each list
18 for ( int count = 0; count < colors.length; count++ ) {
19 link.add( colors[ count ] );
20 link2.add( colors2[ count ] );
21 }
22
23 link.addAll( link2 ); // concatenate lists
24 link2 = null; // release resources
25
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
ListTest.java
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
printList( link );
uppercaseStrings( link );
printList( link );
System.out.print( "\nDeleting elements 4 to 6..." );
removeItems( link, 4, 7 );
printList( link );
printReversedList( link );
} // end constructor ListTest
// output List contents
public void printList( List list )
{
System.out.println( "\nlist: " );
for ( int count = 0; count < list.size(); count++ )
System.out.print( list.get( count ) + " " );
System.out.println();
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
ListTest.java
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// locate String objects and convert to uppercase
private void uppercaseStrings( List list )
{
ListIterator iterator = list.listIterator();
while ( iterator.hasNext() ) {
Object object = iterator.next(); // get item
if ( object instanceof String ) // check for String
iterator.set( ( ( String ) object ).toUpperCase() );
}
}
// obtain sublist and use clear method to delete sublist items
private void removeItems( List list, int start, int end )
{
list.subList( start, end ).clear(); // remove items
}
// print reversed list
private void printReversedList( List list )
{
ListIterator iterator = list.listIterator( list.size() );
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
ListTest.java
76
77
78
79
80
81
82
83
84
85
86
87
88
System.out.println( "\nReversed List:" );
// print list in reverse order
while( iterator.hasPrevious() )
System.out.print( iterator.previous() + " " );
}
public static void main( String args[] )
{
new ListTest();
}
} // end class ListTest
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
ListTest.java
Output:
list:
black yellow green blue violet silver gold white brown blue gray silver
list:
BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVER
Deleting elements 4 to 6...
list:
BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER
Reversed List:
SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
UsingToArray.java
1 // UsingToArray.java
2 // Using method toArray.
3 import java.util.*;
4
5 public class UsingToArray {
6
7 // create LinkedList, add elements and convert to array
8 public UsingToArray()
9 {
10 String colors[] = { "black", "blue", "yellow" };
11
12 LinkedList links = new LinkedList( Arrays.asList( colors ) );
13
14 links.addLast( "red" ); // add as last item
15 links.add( "pink" ); // add to the end
16 links.add( 3, "green" ); // add at 3rd index
17 links.addFirst( "cyan" ); // add as first item
18
19 // get LinkedList elements as an array
20 colors = ( String [] ) links.toArray( new String[ links.size() ] );
21
22 System.out.println( "colors: " );
23
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
UsingToArray.java
24
25
26
27
28
29
30
31
32
33
for ( int count = 0; count < colors.length; count++ )
System.out.println( colors[ count ] );
}
public static void main( String args[] )
{
new UsingToArray();
}
} // end class UsingToArray
Output:
colors:
cyan
black
blue
yellow
green
red
pink
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections - Algorithms
• Collections Framework provides set of
algorithms
o
Implemented as static methods
 List algorithms
 sort
 binarySearch
 reverse
 shuffle
 fill
 copy
 Collection algorithms
 min
 max
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections – Algorithms Sort
• sort
o
Sorts List elements
 Order is determined by natural order of elements’ type
 Relatively fast
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Sort1.java
1 // Sort1.java
2 // Using algorithm sort.
3 import java.util.*;
4
5 public class Sort1 {
6 private static final String suits[] =
7 { "Hearts", "Diamonds", "Clubs", "Spades" };
8
9 // display array elements
10 public void printElements()
11 {
12 // create ArrayList
13 List list = new ArrayList( Arrays.asList( suits ) );
14
15 // output list
16 System.out.println( "Unsorted array elements:\n" + list );
17
18 Collections.sort( list ); // sort ArrayList
19
20 // output list
21 System.out.println( "Sorted array elements:\n" + list );
22 }
23
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Sort1.java
24
25
26
27
28
29
public static void main( String args[] )
{
new Sort1().printElements();
}
} // end class Sort1
Output:
Unsorted array elements:
[Hearts, Diamonds, Clubs, Spades]
Sorted array elements:
[Clubs, Diamonds, Hearts, Spades]
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections - Algorithm shuffle
• shuffle
o
Randomly orders List elements
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Cards.java
1 // Cards.java
2 // Using algorithm shuffle.
3 import java.util.*;
4
5 // class to represent a Card in a deck of cards
6 class Card {
7 private String face;
8 private String suit;
9
10 // initialize a Card
11 public Card( String initialface, String initialSuit )
12 {
13 face = initialface;
14 suit = initialSuit;
15 }
16
17 // return face of Card
18 public String getFace()
19 {
20 return face;
21 }
22
23 // return suit of Card
24 public String getSuit()
25 {
26 return suit;
27 }
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Cards.java
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// return String representation of Card
public String toString()
{
StringBuffer buffer = new StringBuffer( face + " of " + suit );
buffer.setLength( 20 );
return buffer.toString();
}
} // end class Card
// class Cards declaration
public class Cards {
private static final String suits[] =
{ "Hearts", "Clubs", "Diamonds", "Spades" };
private static final String faces[] = { "Ace", "Deuce", "Three",
"Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King" };
private List list;
// set up deck of Cards and shuffle
public Cards()
{
Card deck[] = new Card[ 52 ];
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Cards.java
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
for ( int count = 0; count < deck.length; count++ )
deck[ count ] = new Card( faces[ count % 13 ],
suits[ count / 13 ] );
list = Arrays.asList( deck ); // get List
Collections.shuffle( list ); // shuffle deck
}
// output deck
public void printCards()
{
int half = list.size() / 2 - 1;
for ( int i = 0, j = half + 1; i <= half; i++, j++ )
System.out.println( list.get( i ).toString() + list.get( j ) );
}
public static void main( String args[] )
{
new Cards().printCards();
}
} // end class Cards
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Cards.java
King of Diamonds Jack of Spades
Four of Diamonds Six of Clubs
King of Hearts Nine of Diamonds
Three of Spades Four of Spades
Four of Hearts Seven of Spades
Five of Diamonds Eight of Hearts
Queen of Diamonds Five of Hearts
Seven of Diamonds Seven of Hearts
Nine of Hearts Three of Clubs
Ten of Spades Deuce of Hearts
Three of Hearts Ace of Spades
Six of Hearts Eight of Diamonds
Six of Diamonds Deuce of Clubs
Ace of Clubs Ten of Diamonds
Eight of Clubs Queen of Hearts
Jack of Clubs Ten of Clubs
Seven of Clubs Queen of Spades
Five of Clubs Six of Spades
Nine of Spades Nine of Clubs
King of Spades Ace of Diamonds
Ten of Hearts Ace of Hearts
Queen of Clubs Deuce of Spades
Three of Diamonds King of Clubs
Four of Clubs Jack of Diamonds
Eight of Spades Five of Spades
Jack of Hearts Deuce of Diamonds
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
reverse, fill, copy, max, min
• reverse
o
Reverses the order of List elements
• fill
o
Populates List elements with values
• copy
o
Creates copy of a List
• max
o
Returns largest element in List
• min
o
Returns smallest element in List
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Algorithms1.java
1 // Algorithms1.java
2 // Using algorithms reverse, fill, copy, min and max.
3 import java.util.*;
4
5 public class Algorithms1 {
6 private String letters[] = { "P", "C", "M" }, lettersCopy[];
7 private List list, copyList;
8
9 // create a List and manipulate it with methods from Collections
10 public Algorithms1()
11 {
12 list = Arrays.asList( letters ); // get List
13 lettersCopy = new String[ 3 ];
14 copyList = Arrays.asList( lettersCopy );
15
16 System.out.println( "Initial list: " );
17 output( list );
18
19 Collections.reverse( list ); // reverse order
20 System.out.println( "\nAfter calling reverse: " );
21 output( list );
22
23 Collections.copy( copyList, list ); // copy List
24 System.out.println( "\nAfter copying: " );
25 output( copyList );
26
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Algorithms1.java
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Collections.fill( list, "R" ); // fill list with Rs
System.out.println( "\nAfter calling fill: " );
output( list );
} // end constructor
// output List information
private void output( List listRef )
{
System.out.print( "The list is: " );
for ( int k = 0; k < listRef.size(); k++ )
System.out.print( listRef.get( k ) + " " );
System.out.print( "\nMax: " + Collections.max( listRef ) );
System.out.println( " Min: " + Collections.min( listRef ) );
}
public static void main( String args[] )
{
new Algorithms1();
}
} // end class Algorithms1
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Algorithms1.java
Output:
Initial list:
The list is: P C M
Max: P Min: C
After calling reverse:
The list is: M C P
Max: P Min: C
After copying:
The list is: M C P
Max: P Min: C
After calling fill:
The list is: R R R
Max: R Min: R
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections - Algorithm binarySearch
• binarySearch
o
Locates Object in List
 Returns index of Object in List if Object exists
 Returns negative value if Object does not exist
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
BinarySearchTest.java
1 // BinarySearchTest.java
2 // Using algorithm binarySearch.
3 import java.util.*;
4
5 public class BinarySearchTest {
6 private static final String colors[] = { "red", "white",
7 "blue", "black", "yellow", "purple", "tan", "pink" };
8 private List list; // List reference
9
10 // create, sort and output list
11 public BinarySearchTest()
12 {
13 list = new ArrayList( Arrays.asList( colors ) );
14 Collections.sort( list ); // sort the ArrayList
15 System.out.println( "Sorted ArrayList: " + list );
16 }
17
18 // search list for various values
19 private void printSearchResults()
20 {
21 printSearchResultsHelper( colors[ 3 ] ); // first item
22 printSearchResultsHelper( colors[ 0 ] ); // middle item
23 printSearchResultsHelper( colors[ 7 ] ); // last item
24 printSearchResultsHelper( "aardvark" ); // below lowest
25 printSearchResultsHelper( "goat" ); // does not exist
26 printSearchResultsHelper( "zebra" ); // does not exist
27 }
28
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
BinarySearchTest.java
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// helper method to perform searches
private void printSearchResultsHelper( String key )
{
int result = 0;
System.out.println( "\nSearching for: " + key );
result = Collections.binarySearch( list, key );
System.out.println( ( result >= 0 ? "Found at index " + result :
"Not Found (" + result + ")" ) );
}
public static void main( String args[] )
{
new BinarySearchTest().printSearchResults();
}
}
Sorted ArrayList: black blue pink purple red tan white yellow
Searching for: black
Found at index 0
Searching for: red
Found at index 4
Searching for: pink
Found at index 2
Searching for: aardvark
Not Found (-1)
Searching for: goat
Not Found (-3)
Searching for: zebra
Not Found (-9)
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections - Sets
• Cannot contain duplicate elements
• Models the mathematical set abstraction
• A SortedSet is a Set that maintains its
elements in ascending order
• HashSet
o
o
Stores elements in hash table
HashSet is much faster but offers no ordering
guarantees
• TreeSet
o
o
Stores elements in tree
Stores its elements in a red-black tree, guarantees the
order of iteration
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
SetTest.java
1 // SetTest.java
2 // Using a HashSet to remove duplicates.
3 import java.util.*;
4
5 public class SetTest {
6 private static final String colors[] = { "red", "white", "blue",
7 "green", "gray", "orange", "tan", "white", "cyan",
8 "peach", "gray", "orange" };
9
10 // create and output ArrayList
11 public SetTest()
12 {
13 List list = new ArrayList( Arrays.asList( colors ) );
14 System.out.println( "ArrayList: " + list );
15 printNonDuplicates( list );
16 }
17
18 // create set from array to eliminate duplicates
19 private void printNonDuplicates( Collection collection )
20 {
21 // create a HashSet and obtain its iterator
22 Set set = new HashSet( collection );
23 Iterator iterator = set.iterator();
24
25 System.out.println( "\nNonduplicates are: " );
26
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
SetTest.java
27
28
29
30
31
32
33
34
35
36
37
38
while ( iterator.hasNext() )
System.out.print( iterator.next() + " " );
System.out.println();
}
public static void main( String args[] )
{
new SetTest();
}
} // end class SetTest
ArrayList: [red, white, blue, green, gray, orange, tan, white,
cyan, peach, gray, orange]
Nonduplicates are:
red cyan white tan gray green orange blue peach
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
SortedSetTest.java
1 // SortedSetTest.java
2 // Using TreeSet and SortedSet.
3 import java.util.*;
4
5 public class SortedSetTest {
6 private static final String names[] = { "yellow", "green",
7 "black", "tan", "grey", "white", "orange", "red", "green" };
8
9 // create a sorted set with TreeSet, then manipulate it
10 public SortedSetTest()
11 {
12 SortedSet tree = new TreeSet( Arrays.asList( names ) );
13
14 System.out.println( "set: " );
15 printSet( tree );
16
17 // get headSet based upon "orange"
18 System.out.print( "\nheadSet (\"orange\"): " );
19 printSet( tree.headSet( "orange" ) );
20
21 // get tailSet based upon "orange"
22 System.out.print( "tailSet (\"orange\"): " );
23 printSet( tree.tailSet( "orange" ) );
24
25 // get first and last elements
26 System.out.println( "first: " + tree.first() );
27 System.out.println( "last : " + tree.last() );
28 }
29
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
SortedSetTest.java
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// output set
private void printSet( SortedSet set )
{
Iterator iterator = set.iterator();
while ( iterator.hasNext() )
System.out.print( iterator.next() + " " );
System.out.println();
}
public static void main( String args[] )
{
new SortedSetTest();
}
} // end class SortedSetTest
set:
black green grey orange red tan white yellow
headSet ("orange"): black green grey
tailSet ("orange"): orange red tan white yellow
first: black
last : yellow
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Collections - Maps
• Associates keys to values
• Cannot contain duplicate keys
o Called one-to-one mapping
• Map allows iterating over keys, values, or key-value
pairs; Hashtable did not provide 3rd option.
• Map provides safe way to remove entries in the midst of
iteration;
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
MapTest.java
1 // WordTypeCount.java
2 // Program counts the number of occurrences of each word in a string
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.util.*;
6 import javax.swing.*;
7
8 public class WordTypeCount extends JFrame {
9 private JTextArea inputField;
10 private JLabel prompt;
11 private JTextArea display;
12 private JButton goButton;
13
14 private Map map;
15
16 public WordTypeCount()
17 {
18 super( "Word Type Count" );
19 inputField = new JTextArea( 3, 20 );
20
21 map = new HashMap();
22
23 goButton = new JButton( "Go" );
24 goButton.addActionListener(
25
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
MapTest.java
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
new ActionListener() { // inner class
public void actionPerformed( ActionEvent event )
{
createMap();
display.setText( createOutput() );
}
} // end inner class
); // end call to addActionListener
prompt = new JLabel( "Enter a string:" );
display = new JTextArea( 15, 20 );
display.setEditable( false );
JScrollPane displayScrollPane = new JScrollPane( display );
// add components to GUI
Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( prompt );
container.add( inputField );
container.add( goButton );
container.add( displayScrollPane );
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
MapTest.java
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
setSize( 400, 400 );
show();
} // end constructor
// create map from user input
private void createMap()
{
String input = inputField.getText();
StringTokenizer tokenizer = new StringTokenizer( input );
while ( tokenizer.hasMoreTokens() ) {
String word = tokenizer.nextToken().toLowerCase(); // get word
// if the map contains the word
if ( map.containsKey( word ) ) {
Integer count = (Integer) map.get( word ); // get value
// increment value
map.put( word, new Integer( count.intValue() + 1 ) );
}
else // otherwise add word with a value of 1 to map
map.put( word, new Integer( 1 ) );
} // end while
} // end method createMap
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
MapTest.java
80
81 // create string containing map values
82 private String createOutput() {
83 StringBuffer output = new StringBuffer( "" );
84 Iterator keys = map.keySet().iterator();
85
86 // iterate through the keys
87 while ( keys.hasNext() ) {
88 Object currentKey = keys.next();
89
90 // output the key-value pairs
91 output.append( currentKey + "\t" +
92 map.get( currentKey ) + "\n" );
93 }
94
95 output.append( "size: " + map.size() + "\n" );
96 output.append( "isEmpty: " + map.isEmpty() + "\n" );
97
98 return output.toString();
99
100 } // end method createOutput
101
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
MapTest.java
102
103
104
105
106
107
108
public static void main( String args[] )
{
WordTypeCount application = new WordTypeCount();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class WordTypeCount
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Summary

The Java Collections Framework hierarchy consists of two
distinct interface trees:
 The first tree starts with the Collection interface, which provides for the basic
functionality used by all collections, such as add and remove methods. Its
subinterfaces — Set, List, and Queue — provide for more specialized
collections.
 The Set interface does not allow duplicate elements. This can be useful for storing
collections such as a deck of cards or student records. The Set interface has a
subinterface, SortedSet, that provides for ordering of elements in the set.
 The List interface provides for an ordered collection, for situations in which you
need precise control over where each element is inserted. You can retrieve
elements from a List by their exact position.
 The Queue interface enables additional insertion, extraction, and inspection
operations. Elements in a Queue are typically ordered in on a FIFO basis.
 The second tree starts with the Map interface, which maps keys and values
similar to a Hashtable.Map's subinterface, SortedMap, maintains its key-value
pairs in ascending order or in an order specified by aComparator.

These interfaces allow collections to be manipulated
independently of the details of their representation.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Summary (cont)

The Java Collections Framework provides several general-purpose
implementations of the core interfaces:







For the Set interface, HashSet is the most commonly used implementation.
For the List interface, ArrayList is the most commonly used implementation.
For the Map interface, HashMap is the most commonly used implementation.
For the Queue interface, LinkedList is the most commonly used implementation.
Each of the general-purpose implementations provides all optional
operations contained in its interface.The Java Collections Framework
also provides several special-purpose implementations for situations
that require nonstandard performance, usage restrictions, or other
unusual behavior.
The Collections class (as opposed to the Collection interface),
provides static methods that operate on or return collections, which
are known as Wrapper implementations.
Finally, there are several Convenience implementations, which can
be more efficient than general-purpose implementations when you
don't need their full power. The Convenience implementations are
made available through static factory methods.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
04e-BM/NS/HDCV/FSOFT v2/3
Q&A
© FPT SOFTWARE – TRAINING MATERIAL – Internal use
108
04e-BM/NS/HDCV/FSOFT v2/3
Download