欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
Java in a Nutshell, 4th Edition(1/3)

The Java Platform

by David Flanagan

In this excerpt from Chapter 4 of Java in a Nutshell, 4th Edition,David Flanagan shows you a number of the Java 2SE platform packages,using examples of the most useful classes in these packages.

Chapters 2 and 3 documented the Java programminglanguage. This chapter switches gears and covers the Java platform -- a vast collection of predefined classes available toevery Java program, regardless of the underlying host system onwhich it is running. The classes of the Java platform are collectedinto related groups, known as packages. Thischapter begins with an overview of the packages of the Java platformthat are documented in this book. It then moves on to demonstrate,in the form of short examples, the most useful classes in thesepackages. Most of the examples are code snippets only, not fullprograms you can compile and run. For fully fleshed-out, real-worldexamples, see Java Examples in a Nutshell (O'Reilly).That book expands greatly on this chapter and is intended as acompanion to this one.

Java Platform Overview

Table 1-1 summarizes the key packages ofthe Java platform that are covered in this book.

Table 1-1. Key packages of the Java platform

Package Description
java.beans

The JavaBeans component model for reusable, embeddable software components.

java.beans.beancontext

Additional classes that define bean context objects that hold and provide services to the JavaBeans objects they contain.

java.io

Classes and interfaces for input and output. Although some of the classes in this package are for working directly with files, most are for working with streams of bytes or characters.

java.lang

The core classes of the language, such as String, Math, System, Thread, and Exception.

java.lang.ref

Classes that define weak references to objects. A weak reference is one that does not prevent the referent object from being garbage-collected.

java.lang.reflect

Classes and interfaces that allow Java programs to reflect on themselves by examining the constructors, methods, and fields of classes.

java.math

A small package that contains classes for arbitrary-precision integer and floating-point arithmetic.

java.net

Classes and interfaces for networking with other systems.

java.nio

Buffer classes for the New I/O API.

java.nio.channels

Channel and selector interfaces and classes for high-performance, nonblocking I/O.

java.nio.charset

Character set encoders and decoders for converting Unicode strings to and from bytes.

java.security

Classes and interfaces for access control and authentication. Supports cryptographic message digests and digital signatures.

java.security.acl

A package that supports access control lists. Deprecated and unused as of Java 1.2.

java.security.cert

Classes and interfaces for working with public-key certificates.

java.security.interfaces

Interfaces used with DSA and RSA public-key encryption.

java.security.spec

Classes and interfaces for transparent representations of keys and parameters used in public-key cryptography.

java.text

Classes and interfaces for working with text in internationalized applications.

java.util

Various utility classes, including the powerful collections framework for working with collections of objects.

java.util.jar

Classes for reading and writing JAR files.

java.util.logging

A flexible logging facility.

java.util.prefs

An API to read and write user and system preferences.

java.util.regex

Text pattern matching using regular expressions.

java.util.zip

Classes for reading and writing ZIP files.

javax.crypto

Classes and interfaces for encryption and decryption of data.

javax.crypto.interfaces

Interfaces that represent the Diffie-Hellman public/private keys used in the Diffie-Hellman key agreement protocol.

javax.crypto.spec

Classes that define transparent representations of keys and parameters used in cryptography.

javax.net

Defines factory classes for creating sockets and server sockets. Enables the creation of socket types other than the default.

javax.net.ssl

Classes for encrypted network communication using the Secure Sockets Layer (SSL).

javax.security.auth

The top-level package for the JAAS API for authentication and authorization.

javax.security.auth.callback

Classes that facilitate communication between a low-level login module and a user through a user interface.

javax.security.auth.kerberos

Utility classes to support network authentication using the Kerberos protocol.

javax.security.auth.login

The LoginContext and related classes for user authentication.

javax.security.auth.spi

Defines the LoginModule interface that is implemented by pluggable user-authentication modules.

javax.security.auth.x500

Utility classes that represent X.500 certificate information.

javax.xml.parsers

A high-level API for parsing XML documents using pluggable DOM and SAX parsers.

javax.xml.transform

A high-level API for transforming XML documents using a pluggable XSLT transformation engine and for converting XML documents between streams, DOM trees, and SAX events.

javax.xml.transform.dom

Concrete XML transformation classes for DOM.

javax.xml.transform.sax

Concrete XML transformation classes for SAX.

javax.xml.transform.stream

Concrete XML transformation classes for XML streams.

org.ietf.jgss

The Java binding of the Generic Security Services API, which defines a single API for underlying security mechanisms such as Kerberos.

org.w3c.dom

Interfaces defined by the World Wide Web Consortium to represent an XML document as a DOM tree.

org.xml.sax

Classes and interfaces for parsing XML documents using the event-based SAX (Simple API for XML) API.

org.xml.sax.ext

Extension classes for the SAX API.

org.xml.sax.helpers

Utility classes for the SAX API.

Table 1-1 does not list all thepackages in the Java platform, only those documented in this book.(And it omits a few "spi" packages that are documented in thisbook but are of interest only to low-level "serviceproviders.") Java also defines numerouspackages for graphics and graphical user interface programming andfor distributed, or enterprise, computing. The graphics and GUIpackages are java.awt andjavax.swing and their many subpackages. Thesepackages, along with the java.applet package,are documented in Java Foundation Classes in aNutshell (O'Reilly). The enterprise packages of Javainclude java.rmi, java.sql,javax.jndi, org.omg.CORBA,org.omg.CosNaming, and all of theirsubpackages. These packages, as well as several standardextensions to the Java platform, are documented inJava Enterprise in a Nutshell (O'Reilly).

Strings and Characters

Strings of text are a fundamental and commonly used data type. InJava, however, strings are not a primitive type, likechar, int, andfloat. Instead, strings are representedby the java.lang.String class, whichdefines many useful methods for manipulatingstrings. String objects areimmutable: once a Stringobject has been created, there is no way to modify the string oftext it represents. Thus, each method that operates on a stringtypically returns a new String object that holds themodified string.

This code shows some of the basic operations you canperform on strings:


// Creating strings
String s = "Now"; // String objects have a special literal syntax
String t = s + " is the time."; // Concatenate strings with + operator
String t1 = s + " " + 23.4; // + converts other values to strings
t1 = String.valueOf('c'); // Get string corresponding to char value
t1 = String.valueOf(42); // Get string version of integer or any value
t1 = object.toString(); // Convert objects to strings with toString()

// String length
int len = t.length(); // Number of characters in the string: 16

// Substrings of a string
String sub = t.substring(4); // Returns char 4 to end: "is the time."
sub = t.substring(4, 6); // Returns chars 4 and 5: "is"
sub = t.substring(0, 3); // Returns chars 0 through 2: "Now"
sub = t.substring(x, y); // Returns chars between pos x and y-1
int numchars = sub.length(); // Length of substring is always (y-x)

// Extracting characters from a string
char c = t.charAt(2); // Get the 3rd character of t: w
char[] ca = t.toCharArray(); // Convert string to an array of characters
t.getChars(0, 3, ca, 1); // Put 1st 3 chars of t into ca[1]-ca[3]

// Case conversion
String caps = t.toUpperCase(); // Convert to uppercase
String lower = t.toLowerCase(); // Convert to lowercase

// Comparing strings
boolean b1 = t.equals("hello"); // Returns false: strings not equal
boolean b2 = t.equalsIgnoreCase(caps); // Case-insensitive compare: true
boolean b3 = t.startsWith("Now"); // Returns true
boolean b4 = t.endsWith("time."); // Returns true
int r1 = s.compareTo("Pow"); // Returns < 0: s comes before "Pow"
int r2 = s.compareTo("Now"); // Returns 0: strings are equal
int r3 = s.compareTo("Mow"); // Returns > 0: s comes after "Mow"
r1 = s.compareToIgnoreCase("pow"); // Returns < 0 (Java 1.2 and later)

// Searching for characters and substrings
int pos = t.indexOf('i'); // Position of first 'i': 4
pos = t.indexOf('i', pos+1); // Position of the next 'i': 12
pos = t.indexOf('i', pos+1); // No more 'i's in string, returns -1
pos = t.lastIndexOf('i'); // Position of last 'i' in string: 12
pos = t.lastIndexOf('i', pos-1); // Search backwards for 'i' from char 11

pos = t.indexOf("is"); // Search for substring: returns 4
pos = t.indexOf("is", pos+1); // Only appears once: returns -1
pos = t.lastIndexOf("the "); // Search backwards for a string
String noun = t.substring(pos+4); // Extract word following "the"

// Replace all instances of one character with another character
String exclaim = t.replace('.', '!'); // Works only with chars, not substrings

// Strip blank space off the beginning and end of a string
String noextraspaces = t.trim();

// Obtain unique instances of strings with intern()
String s1 = s.intern(); // Returns s1 equal to s
String s2 = "Now".intern(); // Returns s2 equal to "Now"
boolean equals = (s1 == s2); // Now can test for equality with ==

The Character Class

As you know, individual characters are represented in Java by theprimitive char type. The Java platform also definesa Character class, which defines useful classmethods for checking the type of a character and for convertingthe case of a character. For example:


char[] text; // An array of characters, initialized somewhere else
int p = 0; // Our current position in the array of characters
// Skip leading whitespace
while((p < text.length) && Character.isWhitespace(text[p])) p++;
// Capitalize the first word of text
while((p < text.length) && Character.isLetter(text[p])) {
text[p] = Character.toUpperCase(text[p]);
p++;
}

The StringBuffer Class

Since String objects are immutable, you cannotmanipulate the characters of an instantiated String. If you need to do this, use ajava.lang.StringBuffer instead:


// Create a string buffer from a string
StringBuffer b = new StringBuffer("Mow");

// Get and set individual characters of the StringBuffer
char c = b.charAt(0); // Returns 'M': just like String.charAt()
b.setCharAt(0, 'N'); // b holds "Now": can't do that with a String!

// Append to a StringBuffer
b.append(' '); // Append a character
b.append("is the time."); // Append a string
b.append(23); // Append an integer or any other value

// Insert Strings or other values into a StringBuffer
b.insert(6, "n't"); // b now holds: "Now isn't the time.23"

// Replace a range of characters with a string (Java 1.2 and later)
b.replace(4, 9, "is"); // Back to "Now is the time.23"

// Delete characters
b.delete(16, 18); // Delete a range: "Now is the time"
b.deleteCharAt(2); // Delete 2nd character: "No is the time"
b.setLength(5); // Truncate by setting the length: "No is"

// Other useful operations
b.reverse(); // Reverse characters: "si oN"
String s = b.toString(); // Convert back to an immutable string
s = b.substring(1,2); // Or take a substring: "i"
b.setLength(0); // Erase buffer; now it is ready for reuse

The CharSequence Interface

In Java 1.4, both the String and theStringBuffer classes implement the newjava.lang.CharSequence interface, which is astandard interface for querying the length of and extracting charactersand subsequences from a readable sequence of characters. Thisinterface is also implemented by thejava.nio.CharBuffer interface, which is part ofthe New I/O API that was introduced in Java 1.4.CharSequence provides a way to perform simpleoperations on strings of characters regardless of the underlyingimplementation of those strings. For example:


/**
* Return a prefix of the specified CharSequence that starts at the first
* character of the sequence and extends up to (and includes) the first
* occurrence of the character c in the sequence. Returns null if c is
* not found. s may be a String, StringBuffer, or java.nio.CharBuffer.
*/
public static CharSequence prefix(CharSequence s, char c) {
int numChars = s.length(); // How long is the sequence?
for(int i = 0; i < numChars; i++) { // Loop through characters in sequence
if (s.charAt(i) == c) // If we find c,
return s.subSequence(0,i+1); // then return the prefix subsequence
}
return null; // Otherwise, return null
}

Pattern Matching with Regular Expressions

In Java 1.4 and later, you can perform textual pattern matchingwith regular expressions. Regular expression support isprovided by the Pattern andMatcher classes of thejava.util.regex package, but theString class defines a number of convenientmethods that allow you to use regular expressions even moresimply. Regular expressions use a fairly complex grammar todescribe patterns of characters. The Java implementation usesthe same regex syntax as the Perl programming language. See thejava.util.regex.Pattern class in for a summary of this syntax or consult agood Perl programming book for further details. For a completetutorial on Perl-style regular expressions, seeMastering Regular Expressions (O'Reilly).

The simplest String method that accepts aregular expression argument is matches(); itreturns true if the string matches thepattern defined by the specified regular expression:


// This string is a regular expression that describes the pattern of a typical
// sentence. In Perl-style regular expression syntax, it specifies
// a string that begins with a capital letter and ends with a period,
// a question mark, or an exclamation point.
String pattern = "^[A-Z].*[\\.?!]$";
String s = "Java is fun!";
s.matches(pattern); // The string matches the pattern, so this returns true.

The matches() method returnstrue only if the entire string is a match for thespecified pattern. Perl programmers should note that thisdiffers from Perl's behavior, in which a match means only that someportion of the string matches the pattern. To determine if astring or any substring matches a pattern, simply alter theregular expression to allow arbitrary characters before andafter the desired pattern. In the following code, the regularexpression characters .* match any number ofarbitrary characters:


s.matches(".*\\bJava\\b.*"); // True if s contains the word "Java" anywhere
// The b specifies a word boundary

If you are already familiar with Perl's regular expressionsyntax, you know that it relies on the liberal use of backslashes toescape certain characters. In Perl, regular expressions arelanguage primitives, and their syntax is part of the languageitself. In Java, however, regular expressions are describedusing strings and are typically embedded in programs usingstring literals. The syntax for Java string literals also usesthe backslash as an escape character, so to include a singlebackslash in the regular expression, you must use twobackslashes. Thus, in Java programming, you will often seedouble backslashes in regular expressions.

In addition to matching, regular expressions can be used forsearch-and-replace operations. ThereplaceFirst() andreplaceAll() methods search a string for thefirst substring or all substrings that match a given patternand replace the string or strings with the specified replacementtext, returning a new string that contains the replacements.For example, you could use this code to ensure that the word"Java" is correctly capitalized in a string s:


s.replaceAll("(?i)\\bjava\\b",// Pattern: the word "java", case-insensitive
"Java"); // The replacement string, correctly capitalized
The replacement string passed to replaceAll()and replaceFirst() need not be a simpleliteral string; it may also include references to text thatmatched parenthesized subexpressions within the pattern. Thesereferences take the form of a dollar sign followed by the numberof the subexpression. (If you are not familiar withparenthesized subexpressions within a regular expression, seejava.util.regex.Pattern in .) For example, tosearch for words such as JavaBean, JavaScript, JavaOS, and JavaVM(but not Java or Javanese), and to replace the Java prefix withthe letter J without altering the suffix, you could use code such as:

s.replaceAll("\\bJava([A-Z]\\w+)", // The pattern
"J$1"); // J followed by the suffix that matched the
// subexpression in parentheses: [A-Z]\\w+

The other new Java 1.4 String method that uses regularexpressions is split(), which returns anarray of the substrings of a string, separated by delimitersthat match the specified pattern. To obtain an array of wordsin a string separated by any number of spaces, tabs, ornewlines, do this:


String sentence = "This is a\n\ttwo-line sentence";
String[] words = sentence.split("[ \t\n\r]+");
An optional second argument specifies the maximum number ofentries in the returned array.

The matches(),replaceFirst(),replaceAll(), and split()methods are suitable for when you use a regularexpression only once. If you want to use a regular expression formultiple matches, you should explicitly use thePattern and Matcherclasses of the java.util.regex package.First, create a Pattern object to representyour regular expression with the staticPattern.compile() method. (Another reason touse the Pattern class explicitly instead ofthe String convenience methods is thatPattern.compile() allows you to specify flagssuch as Pattern.CASE_INSENSITIVE thatglobally alter the way the pattern matching is done.) Note thatthe compile() method can throw aPatternSyntaxException if you pass it aninvalid regular expression string. (This exception is alsothrown by the various String conveniencemethods.) The Pattern class definessplit() methods that are similar to theString.split() methods. For all othermatching, however, you must create aMatcher object with thematcher() method and specify the text to bematched against:


import java.util.regex.*;

Pattern javaword = Pattern.compile("\\bJava(\\w*)", Pattern.CASE_INSENSITIVE);
Matcher m = javaword.matcher(sentence);
boolean match = m.matches(); // True if text matches pattern exactly
Once you have a Matcher object, you cancompare the string to the pattern in various ways. One of themore sophisticated ways is to find all substrings that matchthe pattern:

String text = "Java is fun; JavaScript is funny.";
m.reset(text); // Start matching against a new string
// Loop to find all matches of the string and print details of each match
while(m.find()) {
System.out.println("Found '" + m.group(0) + "' at position " + m.start(0));
if (m.start(1) < m.end(1)) System.out.println("Suffix is " + m.group(1));
}
See the Matcher class in for further details.

String Comparison

The compareTo() and equals()methods of the String class allow you tocompare strings. compareTo() bases itscomparison on the character order defined by the Unicode encoding,while equals() defines string equality asstrict character-by-character equality. These are not always theright methods to use, however. In some languages, the characterordering imposed by the Unicode standard does not match thedictionary ordering used when alphabetizing strings. In Spanish,for example, the letters "ch" are considered a single letter thatcomes after "c" and before "d." When comparing human-readablestrings in an internationalized application, you should use thejava.text.Collator class instead:


import java.text.*;

// Compare two strings; results depend on where the program is run
// Return values of Collator.compare() have same meanings as String.compareTo()
Collator c = Collator.getInstance(); // Get Collator for current locale
int result = c.compare("chica", "coche"); // Use it to compare two strings

StringTokenizer

There are a number of other Java classes that operate on stringsand characters. One notable class isjava.util.StringTokenizer, which you can useto break a string of text into its component words:


String s = "Now is the time";
java.util.StringTokenizer st = new java.util.StringTokenizer(s);
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You can even use this class to tokenize words that are delimitedby characters other than spaces:

String s = "a:b:c:d";
java.util.StringTokenizer st = new java.util.StringTokenizer(s, ":");

Numbers and Math

Java provides the byte,short, int,long, float, anddouble primitive types for representingnumbers. The java.lang package includes thecorresponding Byte,Short, Integer,Long, Float, andDouble classes, each of which is a subclass ofNumber. These classes can be usefulas object wrappers around their primitive types, and they also definesome useful constants:


// Integral range constants: Integer, Long, and Character also define these
Byte.MIN_VALUE // The smallest (most negative) byte value
Byte.MAX_VALUE // The largest byte value
Short.MIN_VALUE // The most negative short value
Short.MAX_VALUE // The largest short value

// Floating-point range constants: Double also defines these
Float.MIN_VALUE // Smallest (closest to zero) positive float value
Float.MAX_VALUE // Largest positive float value

// Other useful constants
Math.PI // 3.14159265358979323846
Math.E // 2.7182818284590452354

Converting Numbers from and to Strings

A Java program that operates on numbers must get its input valuesfrom somewhere. Often, such a programreads a textual representation of a number and mustconvert it to a numeric representation. Thevarious Number subclasses define usefulconversion methods:


String s = "-42";
byte b = Byte.parseByte(s); // s as a byte
short sh = Short.parseShort(s); // s as a short
int i = Integer.parseInt(s); // s as an int
long l = Long.parseLong(s); // s as a long
float f = Float.parseFloat(s); // s as a float (Java 1.2 and later)
f = Float.valueOf(s).floatValue(); // s as a float (prior to Java 1.2)
double d = Double.parseDouble(s); // s as a double (Java 1.2 and later)
d = Double.valueOf(s).doubleValue(); // s as a double (prior to Java 1.2)

// The integer conversion routines handle numbers in other bases
byte b = Byte.parseByte("1011", 2); // 1011 in binary is 11 in decimal
short sh = Short.parseShort("ff", 16); // ff in base 16 is 255 in decimal

// The valueOf() method can handle arbitrary bases between 2 and 36
int i = Integer.valueOf("egg", 17).intValue(); // Base 17!

// The decode() method handles octal, decimal, or hexadecimal, depending
// on the numeric prefix of the string
short sh = Short.decode("0377").byteValue(); // Leading 0 means base 8
int i = Integer.decode("0xff").shortValue(); // Leading 0x means base 16
long l = Long.decode("255").intValue(); // Other numbers mean base 10

// Integer class can convert numbers to strings
String decimal = Integer.toString(42);
String binary = Integer.toBinaryString(42);
String octal = Integer.toOctalString(42);
String hex = Integer.toHexString(42);
String base36 = Integer.toString(42, 36);

Formatting Numbers

Numeric values are often printed differently in differentcountries. For example, many European languages use a comma toseparate the integral part of a floating-point value from thefractional part (instead of a decimal point). Formatting differences can divergeeven further when displaying numbers that represent monetaryvalues. When converting numbers to strings for display,therefore, it is best to use thejava.text.NumberFormat class to perform theconversion in a locale-specific way:


import java.text.*;

// Use NumberFormat to format and parse numbers for the current locale
NumberFormat nf = NumberFormat.getNumberInstance(); // Get a NumberFormat
System.out.println(nf.format(9876543.21)); // Format number for current locale
try {
Number n = nf.parse("1.234.567,89"); // Parse strings according to locale
} catch (ParseException e) { /* Handle exception */ }

// Monetary values are sometimes formatted differently than other numbers
NumberFormat moneyFmt = NumberFormat.getCurrencyInstance();
System.out.println(moneyFmt.format(1234.56)); // Prints $1,234.56 in U.S.

Mathematical Functions

The Math class defines a number of methods thatprovide trigonometric, logarithmic, exponential, and roundingoperations, among others. This class is primarily useful with floating-point values. Forthe trigonometric functions, angles are expressed in radians. Thelogarithm and exponentiation functions are basee, not base 10. Here are some examples:


double d = Math.toRadians(27); // Convert 27 degrees to radians
d = Math.cos(d); // Take the cosine
d = Math.sqrt(d); // Take the square root
d = Math.log(d); // Take the natural logarithm
d = Math.exp(d); // Do the inverse: e to the power d
d = Math.pow(10, d); // Raise 10 to this power
d = Math.atan(d); // Compute the arc tangent
d = Math.toDegrees(d); // Convert back to degrees
double up = Math.ceil(d); // Round to ceiling
double down = Math.floor(d); // Round to floor
long nearest = Math.round(d); // Round to nearest

Random Numbers

The Math class also defines a rudimentary method forgenerating pseudo-random numbers, but thejava.util.Random class is more flexible. Ifyou need very random pseudo-random numbers,you can use the java.security.SecureRandom class:


// A simple random number
double r = Math.random(); // Returns d such that: 0.0 <= d < 1.0

// Create a new Random object, seeding with the current time
java.util.Random generator = new java.util.Random(System.currentTimeMillis());
double d = generator.nextDouble(); // 0.0 <= d < 1.0
float f = generator.nextFloat(); // 0.0 <= f < 1.0
long l = generator.nextLong(); // Chosen from the entire range of long
int i = generator.nextInt(); // Chosen from the entire range of int
i = generator.nextInt(limit); // 0 <= i < limit (Java 1.2 and later)
boolean b = generator.nextBoolean(); // true or false (Java 1.2 and later)
d = generator.nextGaussian(); // Mean value: 0.0; std. deviation: 1.0
byte[] randomBytes = new byte[128];
generator.nextBytes(randomBytes); // Fill in array with random bytes

// For cryptographic strength random numbers, use the SecureRandom subclass
java.security.SecureRandom generator2 = new java.security.SecureRandom();
// Have the generator generate its own 16-byte seed; takes a *long* time
generator2.setSeed(generator2.generateSeed(16)); // Extra random 16-byte seed
// Then use SecureRandom like any other Random object
generator2.nextBytes(randomBytes); // Generate more random bytes

Big Numbers

The java.math package contains theBigInteger and BigDecimalclasses. These classes allow you to work with arbitrary-size andarbitrary-precision integers and floating-point values. For example:


import java.math.*;

// Compute the factorial of 1000
BigInteger total = BigInteger.valueOf(1);
for(int i = 2; i <= 1000; i++)
total = total.multiply(BigInteger.valueOf(i));
System.out.println(total.toString());

In Java 1.4, BigInteger has a method torandomly generate large prime numbers, which is useful in manycryptographic applications:


BigInteger prime =
BigInteger.probablePrime(1024, // 1024 bits long
generator2); // Source of randomness; from
// preceding example

Dates and Times

Java uses several different classes for working with dates andtimes. The java.util.Date class represents aninstant intime (precise down to the millisecond). This class is nothingmore than a wrapper around a long value thatholds the number of milliseconds since midnight GMT, January 1, 1970. Here are two ways to determine thecurrent time:


long t0 = System.currentTimeMillis(); // Current time in milliseconds
java.util.Date now = new java.util.Date(); // Basically the same thing
long t1 = now.getTime(); // Convert a Date to a long value

The Date class has a number ofinteresting-sounding methods, but almost all of them have beendeprecated in favor of methods of thejava.util.Calendar andjava.text.DateFormat classes.

Formatting Dates with DateFormat

To print a date or atime, use the DateFormat class, whichautomatically handles locale-specific conventions for date and timeformatting. DateFormat even works correctly inlocales that use a calendar other than the common era(Gregorian) calendar in use throughout much of the world:


import java.util.Date;
import java.text.*;

// Display today's date using a default format for the current locale
DateFormat defaultDate = DateFormat.getDateInstance();
System.out.println(defaultDate.format(new Date()));

// Display the current time using a short time format for the current locale
DateFormat shortTime = DateFormat.getTimeInstance(DateFormat.SHORT);
System.out.println(shortTime.format(new Date()));

// Display date and time using a long format for both
DateFormat longTimestamp =
DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
System.out.println(longTimestamp.format(new Date()));

// Use SimpleDateFormat to define your own formatting template
// See java.text.SimpleDateFormat for the template syntax
DateFormat myformat = new SimpleDateFormat("yyyy.MM.dd");
System.out.println(myformat.format(new Date()));
try { // DateFormat can parse dates too
Date leapday = myformat.parse("2000.02.29");
}
catch (ParseException e) { /* Handle parsing exception */ }

Date Arithmetic with Calendar

The Date class and its millisecondrepresentation allow only a very simple form of date arithmetic:


long now = System.currentTimeMillis(); // The current time
long anHourFromNow = now + (60 * 60 * 1000); // Add 3,600,000 milliseconds
To perform more sophisticated date and time arithmetic andmanipulate dates in ways humans (rather than computers)typically care about, use thejava.util.Calendar class:

import java.util.*;

// Get a Calendar for current locale and time zone
Calendar cal = Calendar.getInstance();

// Figure out what day of the year today is
cal.setTime(new Date()); // Set to the current time
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR); // What day of the year is it?

// What day of the week does the leap day in the year 2000 occur on?
cal.set(2000, Calendar.FEBRUARY, 29); // Set year, month, day fields
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // Query a different field

// What day of the month is the 3rd Thursday of May, 2001?
cal.set(Calendar.YEAR, 2001); // Set the year
cal.set(Calendar.MONTH, Calendar.MAY); // Set the month
cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY); // Set the day of week
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 3); // Set the week
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); // Query the day in month

// Get a Date object that represents 30 days from now
Date today = new Date(); // Current date
cal.setTime(today); // Set it in the Calendar object
cal.add(Calendar.DATE, 30); // Add 30 days
Date expiration = cal.getTime(); // Retrieve the resulting date

Arrays

The java.lang.System class defines anarraycopy()method that is useful for copying specified elements in one array to aspecified position in a second array. The second array must be the sametype as the first, and it can even be the same array:


char[] text = "Now is the time".toCharArray();
char[] copy = new char[100];
// Copy 10 characters from element 4 of text into copy, starting at copy[0]
System.arraycopy(text, 4, copy, 0, 10);

// Move some of the text to later elements, making room for insertions
System.arraycopy(copy, 3, copy, 6, 7);

In Java 1.2 and later, the java.util.Arrays classdefines useful array-manipulation methods, includingmethods for sorting and searching arrays:


import java.util.Arrays;

int[] intarray = new int[] { 10, 5, 7, -3 }; // An array of integers
Arrays.sort(intarray); // Sort it in place
int pos = Arrays.binarySearch(intarray, 7); // Value 7 is found at index 2
pos = Arrays.binarySearch(intarray, 12); // Not found: negative return value

// Arrays of objects can be sorted and searched too
String[] strarray = new String[] { "now", "is", "the", "time" };
Arrays.sort(strarray); // { "is", "now", "the", "time" }

// Arrays.equals() compares all elements of two arrays
String[] clone = (String[]) strarray.clone();
boolean b1 = Arrays.equals(strarray, clone); // Yes, they're equal

// Arrays.fill() initializes array elements
byte[] data = new byte[100]; // An empty array; elements set to 0
Arrays.fill(data, (byte) -1); // Set them all to -1
Arrays.fill(data, 5, 10, (byte) -2); // Set elements 5, 6, 7, 8, 9 to -2

Arrays can be treated and manipulated as objects in Java. Givenan arbitrary object o, you can use code such asthe following to find out if the objectis an array and, if so, what type of array it is:


Class type = o.getClass();
if (type.isArray()) {
Class elementType = type.getComponentType();
}

Collections

The Java collection framework is a set ofimportant utility classes and interfaces in thejava.util package for working with collectionsof objects. The collection framework defines two fundamentaltypes of collections. A Collection is a groupof objects, while a Map is a set of mappings, orassociations, between objects. A Set is a typeof Collection in which there are no duplicates,and a List is a Collectionin which the elements are ordered. SortedSetand SortedMap are specialized sets and mapsthat maintain their elements in a sorted order.Collection, Set,List, Map,SortedSet, and SortedMap areall interfaces, but the java.util package alsodefines various concrete implementations, such as lists based onarrays and linked lists, and maps and sets based on hashtables orbinary trees. (See the java.util package in for a complete list.) Other important interfacesare Iterator andListIterator, which allow you to loop throughthe objects in a collection. The collection framework is new as ofJava 1.2, but prior to that release you can useVector and Hashtable, whichare approximately the same as ArrayList andHashMap.

In Java 1.4, the Collections API has grown with the addition ofthe RandomAccess marker interface, which isimplemented by List implementations thatsupport efficient random access (i.e., it is implemented byArrayList and Vector but notby LinkedList.) Java 1.4 also introducesLinkedHashMap andLinkedHashSet, which are hashtable-based mapsand sets that preserve the insertion order of elements. Finally,IdentityHashMap is a hashtable-basedMap implementation that uses the== operator to compare key objects rather thanusing the equals() method to compare them.

The following code demonstrates how you might create and performbasic manipulations on sets, lists, and maps:


import java.util.*;

Set s = new HashSet(); // Implementation based on a hashtable
s.add("test"); // Add a String object to the set
boolean b = s.contains("test2"); // Check whether a set contains an object
s.remove("test"); // Remove a member from a set

Set ss = new TreeSet(); // TreeSet implements SortedSet
ss.add("b"); // Add some elements
ss.add("a");
// Now iterate through the elements (in sorted order) and print them
for(Iterator i = ss.iterator(); i.hasNext();)
System.out.println(i.next());

List l = new LinkedList(); // LinkedList implements a doubly linked list
l = new ArrayList(); // ArrayList is more efficient, usually
Vector v = new Vector(); // Vector is an alternative in Java 1.1/1.0
l.addAll(ss); // Append some elements to it
l.addAll(1, ss); // Insert the elements again at index 1
Object o = l.get(1); // Get the second element
l.set(3, "new element"); // Set the fourth element
l.add("test"); // Append a new element to the end
l.add(0, "test2"); // Insert a new element at the start
l.remove(1); // Remove the second element
l.remove("a"); // Remove the element "a"
l.removeAll(ss); // Remove elements from this set
if (!l.isEmpty()) // If list is not empty,
System.out.println(l.size()); // print out the number of elements in it
boolean b1 = l.contains("a"); // Does it contain this value?
boolean b2 = l.containsAll(ss); // Does it contain all these values?
List sublist = l.subList(1,3); // A sublist of the 2nd and 3rd elements
Object[] elements = l.toArray(); // Convert it to an array
l.clear(); // Delete all elements

Map m = new HashMap(); // Hashtable an alternative in Java 1.1/1.0
m.put("key", new Integer(42)); // Associate a value object with a key object
Object value = m.get("key"); // Look up the value associated with a key
m.remove("key"); // Remove the association from the Map
Set keys = m.keySet(); // Get the set of keys held by the Map

Converting to and from Arrays

Arrays of objects and collections serve similar purposes. Itis possible to convert from one to the other:


Object[] members = set.toArray(); // Get set elements as an array
Object[] items = list.toArray(); // Get list elements as an array
Object[] keys = map.keySet().toArray(); // Get map key objects as an array
Object[] values = map.values().toArray(); // Get map value objects as an array

List l = Arrays.asList(a); // View array as an ungrowable list
List l = new ArrayList(Arrays.asList(a)); // Make a growable copy of it

Collections Utility Methods

Just as the java.util.Arrays class defined methods tooperate on arrays, the java.util.Collections classdefines methods to operate on collections. Most notable aremethods to sort and search the elements of collections:


Collections.sort(list);
int pos = Collections.binarySearch(list, "key"); // list must be sorted first
Here are some other interesting Collectionsmethods:

Collections.copy(list1, list2); // Copy list2 into list1, overwriting list1
Collections.fill(list, o); // Fill list with Object o
Collections.max(c); // Find the largest element in Collection c
Collections.min(c); // Find the smallest element in Collection c

Collections.reverse(list); // Reverse list
Collections.shuffle(list); // Mix up list

Set s = Collections.singleton(o); // Return an immutable set with one element o
List ul = Collections.unmodifiableList(list); // Immutable wrapper for list
Map sm = Collections.synchronizedMap(map); // Synchronized wrapper for map

Types, Reflection, and Dynamic Loading

The java.lang.Class class represents datatypes in Java and, along with the classes in thejava.lang.reflect package, gives Java programsthe capability of introspection (or self-reflection); aJava class can look atitself, or any other class, and determine its superclass, whatmethods it defines, and so on.

Class Objects

There are several ways you canobtain a Class object in Java:


// Obtain the Class of an arbitrary object o
Class c = o.getClass();

// Obtain a Class object for primitive types with various predefined constants
c = Void.TYPE; // The special "no-return-value" type
c = Byte.TYPE; // Class object that represents a byte
c = Integer.TYPE; // Class object that represents an int
c = Double.TYPE; // etc; see also Short, Character, Long, Float

// Express a class literal as a type name followed by ".class"
c = int.class; // Same as Integer.TYPE
c = String.class; // Same as "dummystring".getClass()
c = byte[].class; // Type of byte arrays
c = Class[][].class; // Type of array of arrays of Class objects

Reflecting on a Class

Once you have a Class object, you can performsome interesting reflective operations with it:


import java.lang.reflect.*;

Object o; // Some unknown object to investigate
Class c = o.getClass(); // Get its type

// If it is an array, figure out its base type
while (c.isArray()) c = c.getComponentType();

// If c is not a primitive type, print its class hierarchy
if (!c.isPrimitive()) {
for(Class s = c; s != null; s = s.getSuperclass())
System.out.println(s.getName() + " extends");
}

// Try to create a new instance of c; this requires a no-arg constructor
Object newobj = null;
try { newobj = c.newInstance(); }
catch (Exception e) {
// Handle InstantiationException, IllegalAccessException
}

// See if the class has a method named setText that takes a single String
// If so, call it with a string argument
try {
Method m = c.getMethod("setText", new Class[] { String.class });
m.invoke(newobj, new Object[] { "My Label" });
} catch(Exception e) { /* Handle exceptions here */ }

Dynamic Class Loading

Class also provides a simplemechanism for dynamic class loading in Java. For more completecontrol over dynamic class loading, however, you should use ajava.lang.ClassLoader object, typically ajava.net.URLClassLoader. This techniqueis useful, for example, whenyou want to load a class that is named in a configurationfile instead of being hardcoded into your program:


// Dynamically load a class specified by name in a config file
String classname = // Look up the name of the class
config.getProperty("filterclass", // The property name
"com.davidflanagan.filters.Default"); // A default

try {
Class c = Class.forName(classname); // Dynamically load the class
Object o = c.newInstance(); // Dynamically instantiate it
} catch (Exception e) { /* Handle exceptions */ }

The preceding code works only if the class to be loaded is in theclass path. If this is not the case, you can create a customClassLoader object to load a class from apath (or URL) you specify yourself:


import java.net.*;
String classdir = config.getProperty("filterDirectory"); // Look up class path
trying {
ClassLoader loader = new URLClassLoader(new URL[] { new URL(classdir) });
Class c = loader.loadClass(classname);
}
catch (Exception e) { /* Handle exceptions */ }

Dynamic Proxies

Java 1.3 added the Proxy class andInvocationHandler interface to thejava.lang.reflect package.Proxy is a powerful but infrequently used classthat allows you to dynamically create a new class or instance thatimplements a specified interface or set of interfaces. It also dispatches invocations of the interface methods to anInvocationHandler object.

本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請點(diǎn)擊舉報。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
I am rem1x. ? Blog Archive ? GKeyFile–存取你的配置文...
Performance Tips and Tricks in .NET Applications
Chapter 10: Jython and Java Integration
ACCU :: Error logging and patterns
Getting to Know Groovy
Mock Exam II
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導長(cháng)圖 關(guān)注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久