Presentation is loading. Please wait.

Presentation is loading. Please wait.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Exception Handling & Java Utility API.

Similar presentations


Presentation on theme: "© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Exception Handling & Java Utility API."— Presentation transcript:

1 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Exception Handling & Java Utility API

2 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Course Objective Exception Handling Java Utilities classes Java Collection Framework

3 © 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

4 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 EXCEPTION HANDLING Session 1

5 © 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.

6 © 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

7 © 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.

8 © 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.

9 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Throwable Class and Its Subclasses

10 © 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.

11 © 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.

12 © 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.

13 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Example 1. //Note: This class won't compile by design! 2. import java.io.*; 3. import java.util.List; 4. import java.util.ArrayList; 5. public class ListOfNumbers { 6. private List list; 7. private static final int SIZE = 10; 8. public ListOfNumbers () { 9. list = new ArrayList (SIZE); 10. for (int i = 0; i < SIZE; i++) { 11. list.add(new Integer(i)); 12. } 13. } 14. public void writeList() { 15. PrintWriter out = new PrintWriter( new FileWriter("OutFile.txt") ); 16. for (int i = 0; i < SIZE; i++) { 17. out.println("Value at: " + i + " = " + list.get(i) ); 18. } 19. out.close(); 20. } 21. }

14 © 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.

15 © 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.

16 © 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

17 © 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) { }  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.

18 © 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()); }

19 © 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.

20 © 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.

21 © 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.

22 © 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.

23 © 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"); }

24 © 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.

25 © 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.

26 © 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.

27 © 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

28 © 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.

29 © 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

30 © 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.

31 © 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.

32 © 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 { … }

33 © 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;

34 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Example import java.util.EmptyStackException; public class ThrowAnException { private List 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)

35 © 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.

36 © 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.

37 © 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.

38 © 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() + "()“ ); }

39 © 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?

40 © 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.

41 © 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 DuplicatedCustomerException

42 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 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); }

43 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 CustomerException.java public class CustomerException extends BusinessLogicException { private static final String ID = "Customer ID: "; private static final String NAME = "Customer Name: "; private Long customerID; private 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(); }

44 © 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(); }

45 © 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(); }

46 © 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.

47 © 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

48 © 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.

49 © 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.

50 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 UTILITIES CLASSES Session 2

51 © 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 Strings: String & String Buffer classes o Math class o Wrappers:  Boolean  Byte  Character  Double  Float  Integer  Long  Short

52 © 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 char charAt(int index) public String concat(String s) public boolean equals(Object anObject) public boolean equalsIgnoreCase(String s) public int length() public String replace(char old, char new) public String substring(int begin) public String substring(int begin, int end) public String toLowerCase() public String toUpperCase() public String trim()

53 © 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, ever- changing 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 synchronized StringBuffer append(String s) public synchronized StringBuffer insert(int offset, String s) public synchronized StringBuffer reverse() public String toString()

54 © 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),…

55 © 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: o 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.

56 © 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:

57 © 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");

58 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java.lang – Wrappers (cont.) Using Wrapper Conversion Utilities o 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.

59 © 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().

60 © 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().

61 © 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.

62 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JAVA COLLECTIONS FRAMEWORK Session 3

63 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 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… Collections

64 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 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 o Interfaces: abstract data types representing collections. o Implementations: concrete implementations of the collection interfaces. Collections Framework oAlgorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces.

65 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Interface Collection o A Collection represents a group of objects, known as its elements o Some Collection implementations allow duplicate elements and others do not o Some are ordered and others unordered o 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 Provides static methods that manipulate collections o Collections can be manipulated polymorphically Interface Collection and Class Collections

66 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 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); C may be a List, a Set, or some other kind of Collection The statement creates a new ArrayList (an implementation of the List interface), initially containing all of the elements in c More on Collection interface

67 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 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.

68 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 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 Collections - Lists

69 © 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

70 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 CollectionTest.java 28 // remove all String objects 29 removeStrings( list ); 30 31 // output list contents 32 System.out.println( "\n\nArrayList after calling removeStrings: " ); 33 34 for ( int count = 0; count < list.size(); count++ ) 35 System.out.print( list.get( count ) + " " ); 36 37 } // end constructor CollectionTest 38 39 // remove String objects from Collection 40 private void removeStrings( Collection collection ) 41 { 42 Iterator iterator = collection.iterator(); // get iterator 43 44 // loop while collection has items 45 while ( iterator.hasNext() ) 46 47 if ( iterator.next() instanceof String ) 48 iterator.remove(); // remove String object 49 } 50

71 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 CollectionTest.java 51 public static void main( String args[] ) 52 { 53 new CollectionTest(); 54 } 55 56 } // 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]

72 © 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

73 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 ListTest.java 26 printList( link ); 27 28 uppercaseStrings( link ); 29 30 printList( link ); 31 32 System.out.print( "\nDeleting elements 4 to 6..." ); 33 removeItems( link, 4, 7 ); 34 35 printList( link ); 36 37 printReversedList( link ); 38 39 } // end constructor ListTest 40 41 // output List contents 42 public void printList( List list ) 43 { 44 System.out.println( "\nlist: " ); 45 46 for ( int count = 0; count < list.size(); count++ ) 47 System.out.print( list.get( count ) + " " ); 48 49 System.out.println(); 50 }

74 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 ListTest.java 51 52 // locate String objects and convert to uppercase 53 private void uppercaseStrings( List list ) 54 { 55 ListIterator iterator = list.listIterator(); 56 57 while ( iterator.hasNext() ) { 58 Object object = iterator.next(); // get item 59 60 if ( object instanceof String ) // check for String 61 iterator.set( ( ( String ) object ).toUpperCase() ); 62 } 63 } 64 65 // obtain sublist and use clear method to delete sublist items 66 private void removeItems( List list, int start, int end ) 67 { 68 list.subList( start, end ).clear(); // remove items 69 } 70 71 // print reversed list 72 private void printReversedList( List list ) 73 { 74 ListIterator iterator = list.listIterator( list.size() ); 75

75 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 ListTest.java 76 System.out.println( "\nReversed List:" ); 77 78 // print list in reverse order 79 while( iterator.hasPrevious() ) 80 System.out.print( iterator.previous() + " " ); 81 } 82 83 public static void main( String args[] ) 84 { 85 new ListTest(); 86 } 87 88 } // end class ListTest

76 © 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

77 © 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

78 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 UsingToArray.java 24 for ( int count = 0; count < colors.length; count++ ) 25 System.out.println( colors[ count ] ); 26 } 27 28 public static void main( String args[] ) 29 { 30 new UsingToArray(); 31 } 32 33 } // end class UsingToArray Output: colors: cyan black blue yellow green red pink

79 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Collections Framework provides set of algorithms o Implemented as static methods  List algorithms  sort  binarySearch  reverse  shuffle  fill  copy  Collection algorithms  min  max Collections - Algorithms

80 © 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

81 © 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

82 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Sort1.java Output: Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted array elements: [Clubs, Diamonds, Hearts, Spades] 24 public static void main( String args[] ) 25 { 26 new Sort1().printElements(); 27 } 28 29 } // end class Sort1

83 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 shuffle o Randomly orders List elements Collections - Algorithm shuffle

84 © 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 }

85 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Cards.java 28 29 // return String representation of Card 30 public String toString() 31 { 32 StringBuffer buffer = new StringBuffer( face + " of " + suit ); 33 buffer.setLength( 20 ); 34 35 return buffer.toString(); 36 } 37 38 } // end class Card 39 40 // class Cards declaration 41 public class Cards { 42 private static final String suits[] = 43 { "Hearts", "Clubs", "Diamonds", "Spades" }; 44 private static final String faces[] = { "Ace", "Deuce", "Three", 45 "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 46 "Jack", "Queen", "King" }; 47 private List list; 48 49 // set up deck of Cards and shuffle 50 public Cards() 51 { 52 Card deck[] = new Card[ 52 ]; 53

86 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Cards.java 54 for ( int count = 0; count < deck.length; count++ ) 55 deck[ count ] = new Card( faces[ count % 13 ], 56 suits[ count / 13 ] ); 57 58 list = Arrays.asList( deck ); // get List 59 Collections.shuffle( list ); // shuffle deck 60 } 61 62 // output deck 63 public void printCards() 64 { 65 int half = list.size() / 2 - 1; 66 67 for ( int i = 0, j = half + 1; i <= half; i++, j++ ) 68 System.out.println( list.get( i ).toString() + list.get( j ) ); 69 } 70 71 public static void main( String args[] ) 72 { 73 new Cards().printCards(); 74 } 75 76 } // end class Cards

87 © 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

88 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 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 reverse, fill, copy, max, min

89 © 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

90 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Algorithms1.java 27 Collections.fill( list, "R" ); // fill list with Rs 28 System.out.println( "\nAfter calling fill: " ); 29 output( list ); 30 31 } // end constructor 32 33 // output List information 34 private void output( List listRef ) 35 { 36 System.out.print( "The list is: " ); 37 38 for ( int k = 0; k < listRef.size(); k++ ) 39 System.out.print( listRef.get( k ) + " " ); 40 41 System.out.print( "\nMax: " + Collections.max( listRef ) ); 42 System.out.println( " Min: " + Collections.min( listRef ) ); 43 } 44 45 public static void main( String args[] ) 46 { 47 new Algorithms1(); 48 } 49 50 } // end class Algorithms1

91 © 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

92 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 binarySearch o Locates Object in List  Returns index of Object in List if Object exists  Returns negative value if Object does not exist Collections - Algorithm binarySearch

93 © 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

94 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 BinarySearchTest.java 29 // helper method to perform searches 30 private void printSearchResultsHelper( String key ) 31 { 32 int result = 0; 33 34 System.out.println( "\nSearching for: " + key ); 35 result = Collections.binarySearch( list, key ); 36 System.out.println( ( result >= 0 ? "Found at index " + result : 37 "Not Found (" + result + ")" ) ); 38 } 39 40 public static void main( String args[] ) 41 { 42 new BinarySearchTest().printSearchResults(); 43 } 44 45 } 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)

95 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Cannot contain duplicate elements Models the mathematical set abstraction A SortedSet is a Set that maintains its elements in ascending order HashSet o Stores elements in hash table o HashSet is much faster but offers no ordering guarantees TreeSet o Stores elements in tree o Stores its elements in a red-black tree, guarantees the order of iteration Collections - Sets

96 © 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

97 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 SetTest.java 27 while ( iterator.hasNext() ) 28 System.out.print( iterator.next() + " " ); 29 30 System.out.println(); 31 } 32 33 public static void main( String args[] ) 34 { 35 new SetTest(); 36 } 37 38 } // 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

98 © 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

99 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 SortedSetTest.java 30 // output set 31 private void printSet( SortedSet set ) 32 { 33 Iterator iterator = set.iterator(); 34 35 while ( iterator.hasNext() ) 36 System.out.print( iterator.next() + " " ); 37 38 System.out.println(); 39 } 40 41 public static void main( String args[] ) 42 { 43 new SortedSetTest(); 44 } 45 46 } // 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

100 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 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 3 rd option. Map provides safe way to remove entries in the midst of iteration; Collections - Maps

101 © 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

102 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 MapTest.java 26 new ActionListener() { // inner class 27 28 public void actionPerformed( ActionEvent event ) 29 { 30 createMap(); 31 display.setText( createOutput() ); 32 } 33 34 } // end inner class 35 36 ); // end call to addActionListener 37 38 prompt = new JLabel( "Enter a string:" ); 39 display = new JTextArea( 15, 20 ); 40 display.setEditable( false ); 41 42 JScrollPane displayScrollPane = new JScrollPane( display ); 43 44 // add components to GUI 45 Container container = getContentPane(); 46 container.setLayout( new FlowLayout() ); 47 container.add( prompt ); 48 container.add( inputField ); 49 container.add( goButton ); 50 container.add( displayScrollPane ); 51

103 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 MapTest.java 52 setSize( 400, 400 ); 53 show(); 54 55 } // end constructor 56 57 // create map from user input 58 private void createMap() 59 { 60 String input = inputField.getText(); 61 StringTokenizer tokenizer = new StringTokenizer( input ); 62 63 while ( tokenizer.hasMoreTokens() ) { 64 String word = tokenizer.nextToken().toLowerCase(); // get word 65 66 // if the map contains the word 67 if ( map.containsKey( word ) ) { 68 69 Integer count = (Integer) map.get( word ); // get value 70 71 // increment value 72 map.put( word, new Integer( count.intValue() + 1 ) ); 73 } 74 else // otherwise add word with a value of 1 to map 75 map.put( word, new Integer( 1 ) ); 76 77 } // end while 78 79 } // end method createMap

104 © 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

105 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 MapTest.java 102 public static void main( String args[] ) 103 { 104 WordTypeCount application = new WordTypeCount(); 105 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 106 } 107 108 } // end class WordTypeCount

106 © 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.

107 © 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.

108 © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Q&A 108


Download ppt "© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Exception Handling & Java Utility API."

Similar presentations


Ads by Google