Weak HashMap

The WeakHashMap class provides a Map implementation that is based on weakly reachable keys. Because each key object is stored indirectly as the referent of a weak reference, the key is automatically removed from the map only after the garbage collector clears all weak references to the key (inside and outside of the map). NOTE Check out Chapter 6's References API section to learn about weakly reachable and weak references. In contrast, value objects are stored via strong references. These...

Iterable and Collection

Most of the core interfaces are rooted in Iterable and its Collection subinterface. Their generic types are Iterable< T> and Collection< E> . Iterable describes any object that can return its contained objects in some sequence. This interface declares an Iterator< T> iterator() method that returns an Iterator instance for iterating over all of the contained objects. Collection represents a collection of objects that are known as elements. This interface provides methods that are...

Runnable and Thread

Java provides the Runnable interface to identify those objects that supply code for threads to execute via this interface's solitary public void run() method a thread receives no arguments and returns no value. Classes implement Runnable to supply this code, and one of these classes is Thread. Thread provides a consistent interface to the underlying operating system's threading architecture. (The operating system is typically responsible for creating and managing threads.) Thread makes it...

Enum Map

The EnumMap class provides a Map implementation whose keys are the members of the same enum. Null keys are not permitted any attempt to store a null key results in a thrown NullPointerException. Because an enum map is represented internally as an array, an enum map approaches an array in terms of performance. EnumMap supplies the following constructors EnumMap(Class< K> keyType) creates an empty enum map with the specified keyType. This constructor throws NullPointerException when keyType...

Method Description

Static Pattern compile Compile regex and return its Pattern object. This method throws (String when regex's syntax is static Pattern compile Compile regex according to the given flags (a bitset consisting of (String regex,int flags) some combination of Pattern's CANON_EO, CASE_INSENSITIVE, COMMENTS, DOTALL, LITERAL, MULTILINE, UNICODE_CASE, and UNIX_LINES constants) and return its Pattern object. This method throws PatternSyntaxException when regex's syntax is invalid, and...

Math and Strict Math

Int abs int i long abs long l double acos double d Return the absolute value of d. There are four special cases abs -0.0 0.0, abs infinity infinity, abs -infinity infinity, and abs NaN NaN. Return the absolute value of f. There are four special cases abs -0.0 0.0, abs infinity infinity, abs -infinity infinity, and abs NaN NaN. Return the absolute value of i. There is one special case the absolute value of Integer.MIN_VALUE is Integer.MIN_VALUE. Return the absolute value of l. There is one...

Dates Time Zones and Calendars

Internationalized applications must properly handle dates, time zones, and calendars. A date is a recorded temporal moment, a time zone is a set of geographical regions that share a common number of hours relative to Greenwich Mean Time GMT , and a calendar is a system of organizing the passage of time. NOTE GMT identifies the standard geographical location from where all time is measured. UTC, which stands for Coordinated Universal Time, is often specified in place of GMT. Java version 1.0...

File Writer and File Reader

FileWriter is a convenience class for writing characters to files. It subclasses OutputStreamWriter, and its constructors call OutputStreamWriter OutputStream . An instance of this class is equivalent to the following code fragment FileOutputStream fos new FileOutputStream pathname OutputStreamWriter osw osw new OutputStreamWriter fos, In Chapter 4, I presented a logging library with a File class Listing 4-19 that did not incorporate file-writing code. Listing 10-28 addresses this situation by...

P

Package class, 243-247, 268 Package Explorer tab, Eclipse, 19 package reserved word, 152 package statement, 152-153, 179 Packagelnfo application, 244-247 package-private access control level, 83 package-private methods including in Javadoc documentation, 36 packages, 151-160 see also Java packages compile-time search, 154 getPackage method, 271 import statement, 153-154 JAR files, 159-160 logging library example, 155-159 namespaces, 151 naming conventions, 152 package statement, 152-153 runtime...

Thread Synchronization

Throughout its execution, each thread is isolated from other threads because it has been given its own method-call stack. However, threads can still interfere with each other when they access and manipulate shared data. This interference can corrupt the shared data, and this corruption can cause an application to fail. For example, consider a checking account in which a husband and wife have joint access. Suppose that the husband and wife decide to empty this account at the same time without...

Enum Set

Chapter 5 introduced you to traditional enumerated types and their enum replacement. An enum is an enumerated type that is expressed via reserved word enum. Listing 8-11 presents an example of a traditional enumerated type. Listing 8-11. An enumerated type of weekday constants public static final int SUNDAY 1 public static final int MONDAY 2 public static final int TUESDAY 4 public static final int WEDNESDAY 8 public static final int THURSDAY 16 public static final int FRIDAY 32 public static...

File OutputStream and Filelnput Stream

Files are common stream destinations and sources. The concrete FileOutputStream class lets you write a stream of bytes to a file the concrete FileInputStream class lets you read a stream of bytes from a file. FileOutputStream subclasses OutputStream and declares five constructors for creating file output streams. For example, FileOutputStream String pathname creates a file output stream to the existing file identified by pathname. This constructor throws FileNotFoundException when the file does...

Tree Map

The TreeMap class provides a map implementation that is based on a red-black tree. As a result, entries are stored in sorted order of their keys. However, accessing these entries is somewhat slower than with the other Map implementations which are not sorted because links must be traversed. NOTE Check out Wikipedia's Red-black tree entry to learn about red-black trees. TreeMap creates a new, empty tree map that is sorted according to the natural ordering of its keys. All keys inserted into the...

Type Parameter Bounds

List lt E gt 's E type parameter and Map lt K, V gt 's K and V type parameters are examples of unbounded type parameters. You can pass any actual type argument to an unbounded type parameter. It is sometimes necessary to restrict the kinds of actual type arguments that can be passed to a type parameter. For example, you might want to declare a class whose instances can only store instances of classes that subclass an abstract Shape class. To restrict actual type arguments, you can specify an...

Description

Initialize the BigDecimal instance to val's digits. Set the scale to 0. Initialize the BigDecimal instance to the decimal equivalent of val. Set the scale to the number of digits after the decimal point, or 0 if no decimal point is specified. This constructor throws java.lang.NullPointerException when val is null, and java.lang.NumberFormatException when val's string representation is invalid contains letters, for example . Return a new BigDecimal instance that contains the absolute value of...

Big Decimal

In Chapter 2, I introduced a CheckingAccount class with a balance field. I declared this field to be of type int, and included a comment stating that balance represents the number of dollars that can be withdrawn. Alternatively, I could have stated that balance represents the number of pennies that can be withdrawn. Perhaps you are wondering why I did not declare balance to be of type double or float. That way, balance could store values such as 18.26 18 dollars in the whole number part and 26...

Hash Set

The HashSet class provides a set implementation that is backed by a hashtable data structure implemented as a HashMap instance, discussed later, which provides a quick way to determine if an element has already been stored in this structure . Although this class provides no ordering guarantees for its elements, HashSet is much faster than TreeSet. Furthermore, HashSet permits the null reference to be stored in its instances. NOTE Check out Wikipedia's Hash table entry to learn about hashtables....

Filter OutputStream and Filterlnput Stream

Byte array, file, and piped streams pass bytes unchanged to their destinations. Java also supports filter streams that buffer, compress uncompress, encrypt decrypt, or otherwise manipulate an input stream's byte sequence before it reaches its destination. A filter output stream takes the data passed to its write methods the input stream , filters it, and writes the filtered data to an underlying output stream, which might be another filter output stream or a destination output stream such as a...

Collators

Applications perform string comparisons while sorting text. When an application targets English-oriented users, String's compareTo method is probably sufficient for comparing strings. However, this method's binary comparison of each string's Unicode characters is not reliable for languages where the relative order of their characters does not correspond to the Unicode values of these characters. French is one example. Java provides the Collator API with its abstract java.text.Collator...

Regular Expressions API

Text-processing applications often need to match text against patterns. For example, an application might need to locate all occurrences of a word in a text file so that it can replace those occurrences with another word. Java provides regular expressions to help text-processing applications perform pattern matching. A regular expression also known as a regex or regexp is a string-based pattern that represents the set of strings that match this pattern. The pattern consists of literal...

Extending the Enum Class

Enum's generic type is Enum lt E extends Enum lt E gt gt . Although the formal type parameter list looks ghastly, it is not that hard to understand. But first, take a look at Listing 5-42. Listing 5-42. The Coin class as it appears from the perspective of its classfile public final class Coin extends Enum lt Coin gt public static final Coin PENNY new Coin PENNY, 0 public static final Coin NICKEL new Coin NICKEL, 1 public static final Coin DIME new Coin DIME, 2 public static final Coin OUARTER...

Integer Long Short and Byte

Integer, Long, Short, and Byte store 32-bit, 64-bit, 16-bit, and 8-bit integer values in Integer, Long, Short, and Byte objects, respectively. Each class declares MAX_VALUE and MIN_VALUE constants that identify the maximum and minimum values that can be represented by its associated primitive type. These classes also declare the following constructors for initializing their objects Integer int value initializes the Integer object to value. Integer String s converts s's text to a 32-bit integer...

Resource Bundles

An internationalized application contains no hard-coded text or other locale-specific elements such as a specific currency format . Instead, each supported locale's version of these elements is stored outside of the application. NOTE Creating a set of locale-specific elements is known as localization. Java is responsible for storing each locale's version of certain elements, such as currency formats. In contrast, it is your responsibility to store each supported locale's version of other...

Using Meta Annotations in Annotation Type Declarations

Each of the Override, Deprecated, and SuppressWarnings annotation types is itself annotated with meta-annotations annotations that annotate annotation types . For example, Listing 5-18 shows you that the SuppressWarnings annotation type is annotated with two meta-annotations. Listing 5-18. The annotated SuppressWarnings type declaration Retention value SOURCE The Target annotation type, which is located in the java.lang.annotation package, identifies the kinds of application elements to which...

Learning Object Oriented Language Features

Implementation inheritance is inheritance through class extension. 2. Java supports implementation inheritance by providing reserved word extends. 3. A subclass can have only one superclass because Java does not support multiple implementation inheritance. 4. You prevent a class from being subclassed by declaring the class final. 5. The answer is false the super call can only appear in a constructor. 6. If a superclass declares a constructor with one or more parameters, and if a subclass...

Object Serialization and Deserialization

Although you can use the data stream classes to stream primitive type values and String objects, you cannot use these classes to stream non-String objects. Instead, you must use object serialization and deserialization to stream objects of arbitrary types. Object serialization is a virtual machine mechanism for serializing object state into a stream of bytes. Its deserialization counterpart is a virtual machine mechanism for deserializing this state from a byte stream. NOTE An object's state...

Upcasting and Late Binding

Listing 3-9's Point class represents a point as an x-y pair. Because a circle in this example is an x-y pair denoting its center, and has a radius denoting its extent, you can extend Point with a Circle class that introduces a radius field. Check out Listing 3-18. Listing 3-18. A Circle class extending the Point class The fact that Circle is really a Point with a radius implies that you can treat a Circle instance as if it was a Point instance. Accomplish this task by assigning the Circle...

Output StreamWriter and Input StreamReader

The concrete OutputStreamWriter class a Writer subclass is a bridge between an incoming sequence of characters and an outgoing stream of bytes. Characters written to this writer are encoded into bytes according to the default or specified character encoding. NOTE The default character encoding is accessible via the file.encoding system property. Each call to an OutputStreamWriter write method causes an encoder to be called on the given character s . The resulting bytes are accumulated in a...

Processing Annotations

It is not enough to declare an annotation type and use that type to annotate source code. Unless you do something specific with those annotations, they remain dormant. One way to accomplish something specific is to write an application that processes the annotations. Listing 5-21's StubFinder application does just that. Listing 5-21. The StubFinder application public static void main String args throws Exception System.err.println usage java StubFinder classfile return Method methods...

Byte ArrayOutput Stream and Byte ArrayInput Stream

Byte arrays are occasionally useful as stream destinations and sources. The concrete ByteArrayOutputStream class lets you write a stream of bytes to a byte array the concrete ByteArrayInputStream class lets you read a stream of bytes from a byte array. ByteArrayOutputStream declares a pair of constructors. Each constructor creates a byte array output stream with an internal byte array a copy of this array can be returned by calling ByteArrayOutputStream's byte toByteArray method...

Buffered OutputStream and Bufferedlnput Stream

FileOutputStream and FilelnputStream have a performance problem. Each file output stream write method call and file input stream read method call results in a call to one of the underlying platform's native methods, and these native calls slow down I O. NOTE A native method is an underlying platform API function that Java connects to an application via the Java Native Interface JNI . Java supplies reserved word native to identify a native method. For example, the RandomAccessFile class declares...

Float and Double

Float and Double store floating-point and double precision floating-point values in Float and Double objects, respectively. These classes declare the following constants MAX_VALUE identifies the maximum value that can be represented as a float or double. MIN_VALUE identifies the minimum value that can be represented as a float or double. NaN represents 0.0F 0.0F as a float and 0.0 0.0 as a double. NEGATIVE_INFINITY represents -infinity as a float or double. POSITIVE_INFINITY represents infinity...

Reference and Reference Queue

The References API consists of five classes located in the java.lang.ref package. Central to this package are Reference and ReferenceQueue. Reference is the abstract superclass of this package's concrete SoftReference, WeakReference, and PhantomReference subclasses. ReferenceQueue is a concrete class whose instances describe queue data structures. When you associate a ReferenceQueue instance with a Reference subclass object Reference object, for short , the Reference object is added to the...

Soft Reference

The SoftReference class describes a Reference object whose referent is softly reachable. In addition to inheriting Reference's methods and overriding get , this generic class provides the following constructors for initializing a SoftReference object SoftReference T r encapsulates r's reference. The SoftReference object behaves as a soft reference to r. No ReferenceOueue object is associated with this SoftReference object. SoftReference T r, ReferenceOueue lt super T gt q encapsulates r's...

Throwing Exceptions

Now that you have created an InvalidMediaFormatException class, you can declare the Media class and begin to code its convert method. The initial version of this method validates its arguments, and then verifies that the source file's media format agrees with the format implied by its file extension. Check out Listing 4-24. Listing 4-24. Throwing exceptions from the convert method public static void convert String srcName, String dstName throws InvalidMediaFormatException throw new...

Preferences API

Significant applications have preferences, which are configuration items. Examples include the location and size of the application's main window, and the locations and names of files that the application most recently accessed. Preferences are persisted to a file, to a database, or to some other storage mechanism so that they will be available to the application the next time it runs. The simplest approach to persisting preferences is to use the Properties API, which consists of the Properties...

The Road Goes Ever On

Although this book is finished from Apress's perspective, it is not finished from my perspective because the physical limitations of a paperback book prevented me from covering additional topics that are important to Android app developers networking is one example. Accordingly, I am writing six more chapters with the same organization as this book's chapters, but not necessarily with the same style that you will be able to freely download from my website javajeff.mb.ca as PDF files Chapter 11...

Installing and Exploring the JDK

The Java Runtime Environment JRE implements the Java SE platform and makes it possible to run Java programs. The public JRE can be downloaded from the Java SE Downloads page However, the public JRE does not make it possible to develop Java programs. For that task, you need to download and install the Java SE Development Kit JDK , which contains development tools including the Java compiler and a private JRE. NOTE JDK 1.0 was the first JDK to be released in May 1995 . Until JDK 6 arrived, JDK...

Jeff Java Jeff Friesen

Copyright 2010 by Jeff JavaJeff Friesen All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 pbk 978-1-4302-3156-1 ISBN-13 electronic 978-1-4302-3157-8 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names, logos, and...