JDK 1.5 Sample Code

zhaozj2021-02-12  154

http://zamples.com/jspexplorer/samples/samplesjdk1_5.html

JDK 1.5 Sample Code

JDK 1.5 Has Some Very Useful Enhancements. Thanks to Josh Bloch of Sun Microsystems for Helpful Hints.

Early Access: there is an inTeractive Version of this page level fragments to the community at large.

Autoboxing

Java's Distinction Between Primitive Types and their Equivalent Object Types Was Painful. Fortunately, with the advent of autoboxing, That Will Become A Fading Memory.

// Automatically Convert One Type To Another Integer Integer = 1; System.out.Println (Integer); // Mix Integer And INTS in The Same Expression Int I = Integer 3; System.out.Println (i);

Sample Output:

1 4

Collectes

The Collections Framework is Great Enhanced by Generics, Which Allows Collections To Be TypeSafe.

LinkedList StringList = new linkedList (); stringlist.add ("of"); stringlist.add ("course"); stringlist.add ("my"); stringlist.add ("horse"); Iterator Iterator = StringList.iterator (); for (String S: Stringlist) System.out.print (S "");

Sample Output:

Of Course My Horse

ENHANCED for loop

Int arch [] = {1, 2, 3, 4}; int sum = 0; for (int E: array) // e is short for element; I would be confusing sum = E; system.out.println Sum);

Sample Output:

10

ENUMS

Java Programmers Rejoice with the Availability of Enums.

ENUM Suit {Clubs, Diamonds, Hearts, Spades}; for (Suit Suit: suit.values ​​()) System.out.Println (SUIT);

Sample Output:

Clubs Diamonds Hearts Spades

Here is a more complex example.

ENUM COIN {Penny (1), Nickel (5), DIME (10), Quarter (25); COIN (INT VALUE) {this.Value = Value;} private final int value; public int value () {Return Value }}; for (iTerator i = arrays.aslist ()). Iterator (); I.hasNext (); {coin = i.next (); system.out.print (Coin "");} Sample Output:

Penny Nickel Dime Quarter

Formatted Output

Developers now Have the option of use printf type functionality to generated formatted output. Most of The Common C Printf Formatters Are Available.

System.out.printf ("name count / n"); string user = "fflintstone"; int total = 123; system.out.printf ("% s IS% D Years OLD / N", User, Total);

Importing static members

No Longer Is It Necessary To Write

Math.Abs ​​(x) Math.SQRT (x) Math.max (a, b)

We can now IMPORT ONCE AND WRITE IT LIKE this:

Import static java.lang.math. *; public class import {public static void main (string [] args) {double x = 16.0, A = 2.2, b = 3.3; system.out.println (ABS (x)); System.out.println (SQRT (X)); System.out.Println (Max (A, B));}}

Sample Output:

16.0 4.0 3.3

IMPROVED DIAGNOSTIC ABILITY

This Is One of Calvin AustIn's Code Examples.

GENERATINGTASTACKTRACES PROVIDE THISTACKTRACES PROVIDE THREAD.GETALLSTACKTRACE.

StackTraceElement E [] = thread.currentthread (). GetStackTrace (); for (int i = 0; i

Sample Output:

java.lang.Thread.dumpThreads (Native Method) java.lang.Thread.getStackTrace (Thread.java:1333) Class2005.main (Class2005.java:5) {Thread [Reference Handler, 10, system] = [Ljava.lang .StackTraceElement; @ 130c19b, Thread [main, 5, main] = [Ljava.lang.StackTraceElement; @ 1f6a7b9, Thread [Signal Dispatcher, 10, system] = [Ljava.lang.StackTraceElement; @ 7d772e, Thread [Finalizer, 8 System] = [ljava.lang.stackTraceElement; @ 11b86e7} metadata

This Is One of Calvin AustIn's Code Examples.

import java.lang.annotation *;. import java.lang.reflect *;. @Retention (java.lang.annotation.RetentionPolicy.RUNTIME) @interface debug {boolean devbuild () default false; int counter ();} public class MetaTest {final boolean production = true; @debug (devbuild = production, counter = 1) public void testMethod () {} public static void main (String [] args) {MetaTest mt = new MetaTest (); try {Annotation [] A = mt.getClass (). getMethod ("testmethod"). getanNotations (); for (int i = 0; i

Monitoring and manageability

This Is One of Calvin AustIn's Code Examples.

Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java platform. The following code reports the detailed usage of the memory heaps in the Hotspot JVM. This feature is not quite working yet, as you can see .

import java.lang.management *;. import java.util *;. import javax.management *;. public class MemTest {public static void main (String args []) {List pools = ManagementFactory.getMemoryPoolMBeans (); for (ListIterator i = pools.listiterator (); I.hasNext ();) {MemoryPoolmbean P = (MemoryPoolmbean) i.next (); system.out.println ("Memory Type =" P.gettype () "Memory usage = " p.getusage ());}}} sample output:

Memory type = Non-heap memory Memory usage = initSize = 163840, used = 494144, committed = 524288, maxSize = 33554432Memory type = Heap memory Memory usage = initSize = 524288, used = 166440, committed = 524288, maxSize = -1Memory type = heap memory Memory usage = initSize = 65536, used = 0, committed = 65536, maxSize = -1Memory type = heap memory Memory usage = initSize = 65536, used = 0, committed = 65536, maxSize = 0Memory type = heap memory Memory usage = initSize = 1441792, used = 0, committed = 1441792, maxSize = 61997056Memory type = Non-heap memory Memory usage = initSize = 8388608, used = 84360, committed = 8388608, maxSize = 67108864Memory type = Non-heap memory Memory usage = initSize = 8388608, used = 5844808, committed = 8388608, maxSize = 8388608Memory type = Non-heap memory Memory usage = initSize = 12582912, used = 6010560, committed = 12582912, maxSize = 12582912 ## An unexpected error has been detected by HotSpot Virtual Machine: ## sigsegv (0xB) AT PC = 0x42073770, PID = 24776, TID = 1073993792 ## java VM: Java Hotspot (TM) Client VM (1.5.0-Beta-B31 Mixed Mode) # Problematic Frame: # c [libc.so.6 0x73770] __libc_free 0x70 ## An error report file with more information is saved as / tmp /HS_ERR_PID24776.LOG ## if you would Report, please visit: # http://java.sun.com/webapps/bugreport/crash.jsp #variable Arguments

This is Just Using Ellipses as Syntactic Sugar for arrays.

Public class test {// main () Looks Different, Doesn't it? // Try Changing The runtime arguments Above and reer public static void main (string ... args) {system.out.println (args.length " Arguments ");}} Sample Output:

3 arguments

Challenge: Here is a program that reads the name of a class from the command line, followed by a method name It instantiates an object of the specified type, and invokes the method For example, if fed a command line like java.util.. .Date toString, this program will print the current date and time. Of course, this class only works with methods that do not require arguments. The challenge is to use ellipses to specify the variable arguments to invoke.

import java.lang.reflect.Method; public class Test {public static void main (String [] args) {try {Class klass = Class.forName (args [0]); Object instance = klass.newInstance (); Method method = klass.getdeclaredMethod (args [1], new class [] {}); object object = method.invoke (instance, new object [] {}; system.out.println (Object);} catch (java.lang .InstantiationException ie) {ie.printStackTrace ();} catch (java.lang.IllegalAccessException iae) {iae.printStackTrace ();} catch (java.lang.reflect.InvocationTargetException ite) {ite.printStackTrace ();} catch ( Nosuchmethodexception nsme) {nsme.printStackTrace ();} catch (exception e) {// in case method.invoke () throws E.PrintStackTrace ();}}}

Word Frequency Counter

This is Josh Bloch's New and Improved Word Frequency Counter.

Import java.text. *; import java.util. *; public class freq {public static void main (string [] args) {map m = new trememap (); for (String Word: args) {integer freq = m.get (Word); M.PUT (Word, (freq == null? 1: FREQ 1));} system.out.println (m);}} GREP

This is one of Sun's NIO examples This program has a bug:.. Instead of working from a directory name or accepting wildcards, the only way it works is to specify the exact filename that you are looking for ... which defeats the purpose Perhaps YOUER'D LIKE TO FIGURE OUT THE FIX?

We have placed files in the JDK 1.5 shared sandbox called /usr/share/fileXX.data, where XX runs from 1 to 10. These files have privileges that allow them to be read by users, so this example will be able to generate viewable Results. if you attempt read a file for Which You do Not Have Privilege, a java.io.filenotfoundexception Error Will Result.

/ * Search a list of files for lines that match a given regular-expression * pattern Demonstrates NIO mapped byte buffers, charsets, and regular * expressions * / import java.io. *;.. Import java.nio *;. Import java .nio.Channels. *; Import java.nio.charset. *; import java.util.regex. *; public class grep {// charset and decoder for iso-8859-15 private static charset charset = charset.Forname (" ISO-8859-15 "); private static charsetdecoder decoder = charset.newdecoder (); // pattern used to parse line code static pattern linepattern = pattern.Compile (". * / R? / N "); // the input pattern that we're looking for private static pattern pattern; // Compile the pattern from the command line // private static void compile (String pat) {try {pattern = Pattern.compile (pat);} catch (PatternSyntaxException x) { System.err.Println (x.getMessage ()); system.exit (1);}} // use the linepattern to break the given charbuff}, applying // the input pattern to each line to see if we have a Match // PRI Vate Static void grep (file f, charbuffer cb) {matcher lm = linepattern.matcher (cb); // line matcher matcher pm = null; // pattern matcher int lines = 0; while (lm.find ()) {lines Charsequence cs = lm.group (); // the current line if (pm == null) PM = Pattern.matcher (CS); Else Pm.Reset (CS); if (PM.Find ()) System.out .print (f ":" lines ":" CS); IF (lm.end () == Cb.limit ()) Break;}} // search for Occurrence of the Input Pattern in the Given File // private static void grep (file f) throws oException {// open the file and then get a channel from the stream fileinputstream fis = new fileInputstream (f);

FileChannel FC = fis.getChannel (); // Get the file's size and then map it 网 tMORY INT SZ = (int) fc.size (); mappedbytebuffer bb = fc.map (filechannel.mapmode.read_only, 0, sz) ; // decode the file info a char buffer charbuffer cb = decoder.decode (bb); // perform the search grep (f, cb); // Close the channel and the stream fc.close ();} public static void Main (String [] args) {if (args.length <2) {system.err.println ("usage: java grep pattern file ..."); return;} compile (args [0]); for (int i = 1; i

This is file # 2 this is file # 3 this is file # 4 this is file # 5 this is file # 6 this is file # 7 is file # 8 this is file # 9 this is file # 10

转载请注明原文地址:https://www.9cbs.com/read-7414.html

New Post(0)