1. Generic Types
Before 5.0, when we need to extract an element from the collection class, it is necessary to explicitly shape it, such as
ArrayList List = New ArrayList ();
List1.add (0, New Integer (42));
INT TOTAL = (Integer) List1.get (0)). INTVALUE ();
In 5.0, by using Generic Types, it is written to Collection
ArrayList
List.Add (0, New Integer (42));
INT TOTAL = list.get (0) .intValue ();
2. Autoboxing and auto-unboXING OF Primitive Types
Since the Collection (Collection) can only save objects inherited from Object, for the variable of the primitive type, such as int, float, etc., when adding to the collection, you need to use the package class. Integer, Float, etc., such as:
ArrayList
List.Add (0, New Integer (42));
INT TOTAL = (List.get (0)). INTVALUE ();
In 5.0, we no longer need explicitly use these package classes by using autoboxing and auto-unboxing.
ArrayList
List.add (0, 42);
INT TOTAL = list.get (0);
3. ENHANCED FOR
Loop
In general, we need this to do this when we need to travel through arrays and collections:
ArrayList
List.add (0,1);
List.add (1, 2);
Iterator i = list.iterator (); i.hasnext ();) {
Integer value = (integer) i.next ();
}
But after using 5.0 enhanced for loop, our loop can become very simple:
ArrayList
List.add (0,1);
List.add (1, 2);
For (INT i: list) {
System.out.println (i);
}
Similarly, the traversal of arrays is also from the original:
int [] b = new int [3];
For (int i = 0; i Change to: int [] b = new int [3]; For (INT I: B) {system.out.println (i);} to sum up: ENHANCED for loop Syntax: for (FormalParameter: Expression) Statement Equivalent to the original: For (iTerator } FormalParameter = Expression.iteraotor (). Next (); 4. ENUMERATED TYPES From 5.0, J2SE supports enumeration type. Simple enumeration is as follows: Public enum color {red, blue, green;}; Public static void main (String [] args) { For (Color C: color.values ()) { System.out.println (C); } } Output Red Blue Green Slightly complicated use, you can increase the definition of enumeration type: Public Enum Color {Red (1), Blue (5), Green (7); Private int value; COLOR (int value) {this.value = value; Public int value () {return this.value; } Public static void main (String [] args) { For (Color C: color.values ()) { System.out.println (C); System.out.println (C.Value () == 1); } } The output is: Red True Blue False Green False This part of this is in this part of the statement: Private int value; COLOR (int value) {this.value = value; Public int value () {return this.value; Equivalent and declaring a Color class: Public class color { Private int value; COLOR (int value) {this.value = value; Public int value () {return this.value; } Also, the enumeration can also be used in the Switch structure, like Switch (c) { Case red: ... Case Blue: ... } 5. Static import Previously, when we want to use a Static variable in a class, if we need to make a complete writing, but we can write Center by using Static Import, ie: Import static java.awt.borderLayout. * // Import GetContentPane (). add (new jPanel (), center; // STATIC IMPORT uses, so that we can only reference a STATIC variable without introducing a class. 6. Formatted Output and formatted INPUT Formatted Output allows us to format variables in the printf method of class C, format the output, such as system.out.printf ("% s% 5d% n", user, total); 7. Varargs Take a look at the example of 5.0: Public class test { Public test () {} Public void out (string ... args) { For (String S: args) { System.out.println (s); } } Public static void main (String [] args) { Test T = New Test (); T.out ("a", "b", "c"); } } It can be noted that in the parameter table of the OUT method, our parameter declaration is ... args, this is the 5.0 introduced VARARGS concept, that is, allow you to communicate multiple parameters at a time, the same effect, if you need to implement it before 5.0, we may The parameter list of the method is required to be declared as an array, or a collection, and then encapsulate the parameters to a array or a collection when calling the method. which is: Public void out (string [] args) {} OUT (new string [] {"a", "b", "c"}); 8. Synchronization Collection - Queue, BlockingQueue A new set class for increasing synchronization performance is added to J2SE 5.0. Queue is a FIFO queue, and her role is mainly to improve concurrency access performance, and she is the difference between her List, including: 1. She provides some new ways for adding an element of Offer () for deleting the elements of POLL () for obtaining the PEAK () of the first element. These operations with the original add (), Remove () difference lies in that the original add (), remove (), and Element () will throw an exception when the required operation fails, and new offer () and poll () No, when the queue cannot accommodate the new element, Offer () directly returns, when the queue does not have element, the poll () operation returns NULL. example: Public class test { Private arrayblockingqueue Public test (int Capacity) { List = new arrayblockingQueue } Public Void Add (int size) { For (int i = 0; i List.Add (i); OUTPUT (); } } Public void output () { For (INT i: list) { System.out.print (i ""); } } Public static void main (String [] args) { Test T = New Test (2); T.ADD (3); } } Add 3 elements to a queue with a capacity of 2, and his output is: ======= Start ============================================= ===== 0 ========================================= ================================================================================================================================================ ====== ======= Start ============================================= ===== 0 1 ========================================= ================================================================================================================================================ ====== Exception in thread "main" java.lang.illegalStateException: Queue Full AT java.util.abstractqueue.add (unknown source) At test.add (test.java:14) At test.main (Test.java: 32) Modify the above code to: Public Void Add (int size) { For (int i = 0; i List.offer (i); OUTPUT (); } } The output is: ======= Start ============================================= ===== 0 ========================================= ================================================================================================================================================ ====== ======= Start ============================================= ===== 0 1 ========================================= ================================================================================================================================================ ====== ======= Start ============================================= ===== 0 1 ========================================= ================================================================================================================================================ ====== 2. BlockingQueue is a sub-interface of Queue, which provides a new operation, take () and put (), when the queue does not have space, and the thread wants to add an element to the queue by PUT () Blocking. Similarly, when the queue has no space, the thread wants to get an element through Take () to get an element, and threads will also be blocked. With BlockingQueeu, we can easily achieve producers and consumer issues. example: Producer: Public class producer extends thread { Private blockingqueue queue; PRIVATE INT COUNT; Public Producer (BlockingQueue Queue) { THIS.QUEUE = Queue; count = 0; } Public void run () { While (true) { Try { Queue.put (product ()); } catch (exception e) { E.PrintStackTrace (); } } } PRIVATE INTEGER PRODUCE () { System.out.println ("Produce:" Count); Return New Integer (Count ); } } consumer: Public class consumer extends thread { Private blockingqueue queue; Private int ID; Public Consumer (BlockingQueue Queue) { THIS.QUEUE = Queue; } Public void run () { While (true) { Try { Thread.currentthread (). SLEEP (STEP); Consume (Integer Queue.Take ()); } catch (exception e) { E.PrintStackTrace (); } } } Private Void Consume (Integer i) { System.out.println ("/ T / T Consume:" i); } } test program: Public class cptest { Public static void main (String [] args) { ArrayBlockingQueue Queue = New ArrayBlockingQueue (3); Consumer C1 = New Consumer (Queue); Consumer C2 = New Consumer (Queue); Producer P = New Product (Queue); C1.Start (); C2.Start (); p.Start (); } } 3. PriorityQueue provides a priority sorting. She will sort all the added elements according to the natural order of the elements, and the custom COMPARATOR implementation can be changed by initialization, and their order can be changed. Note: The Iterator returned by priorityQueue does not guarantee the value in the queue in order. example: Public class pqtest { Private priorityQueue Public Pqtest (int Capacity, Comparetor COM) { Queue = New priorityQueue Public Void Add (int size) { For (int i = 0; i Queue.offer (i); } } Public void output () { For (INT i: queue) { System.out.print (i ""); } System.out.println (); For (int i = 0; i <5; i ) System.out.print (queue.poll () ""); } Public static void main (String [] args) { Pqtest T = New PQTEST (6, New Pqcomparator ()); T.ADD (5); T.output (); } } The Comparator is implemented as: Public Class Pqcomparator Implements Comparator Public Int Compare (Integer I1, Integer I2) { Return -1 * (i1.intValue () - I2.intValue ()); } } The output is: ======= Start ============================================= ===== 4 3 1 0 2 4 3 2 1 0 ========================================= ================================================================================================================================================ ====== 9. Synchronous (Concurrent) EXECUTOR interface The Executor interface provides a management tool similar to the thread pool. Used to submit the runnable object in Executor, the remaining starting thread, etc., there will be a corresponding implementation class to complete. The ScheduledExecutorService increases than ExecutorService, and the time control, that is, the user can additionally define the start timing of the task when submitted, and subsequent execution intervals and delays. example: task: Public Class Etask Implements Runnable { Private int ID = 0; Public ETASK (INT ID) { THIS.ID = ID; } Public void run () { Try { System.out.Println (ID "start"); thread.sleep (1000); System.out.println (ID "Do"); Thread.sleep (1000); System.out.println (ID "EXIT"); } catch (exception e) { E.PrintStackTrace (); } } } Test class: Public class etest { Public static void main (String [] args) { ExecutorService Executor = Executors.newfixedthreadPool (2); For (int i = 0; i <5; i ) { Runnable R = New ETASK (i); Executor.execute (R); } EXECUTOR.SHUTDOWN (); } } Output: 0 Start 1 Start 0 DO 1 do 0 exit 2 START 1 exit 3 Start 2 DO 3 DO 2 exit 3 exit 4 start 4 DO 4 exit 2. FUTURE and CALLABLE Callable is an interface similar to runnable. The difference between his with Runnable is that she can return the result after it is completed. FUTURE is used to get the result of the thread, or cancel the task that has been to Executor. When we obtain the results of the task through the GET () method provided by Future, if the task is not completed, the thread that calls the get () method will be blocked, knowing that the task is completed. Generally we use Future's implementation class FUTURETASK. example: CALLABLE object: Public class eTask imports callable { Private string id = NULL; Public ETASK (String ID) { THIS.ID = ID; } Public String Call () { Try { System.out.println (ID "start"); Thread.sleep (1000); System.out.println (ID "Do"); Thread.sleep (1000); System.out.println (ID "EXIT"); } catch (exception e) { E.PrintStackTrace (); } Return ID; } } Test class: Public class etest { Public static void main (String [] args) { ExecutorService Executor = Executors.newfixedthreadPool (2); For (int i = 0; i <5; i ) { Try { Callable C = New ETASK (String.Valueof (i)); Futuretask ft = new futuretask (c); Executor.execute (ft); System.out.println ("Finish:" ft.get ()); } catch (exception e) { E.PrintStackTrace (); } } EXECUTOR.SHUTDOWN (); } } Output: 0 Start 0 DO0 EXIT Finish: 0 1 Start 1 do 1 exit Finish: 1 2 START ... 3. CompletionService and ExecutorCompletionService CompletionService is similar to a mix of Executor and Queue. We can submit tasks to CompletionService via Submit (), then get the first completed task through Poll (), or to block the next task of the next completion. ExecutorCompletionService is the implementation class of CompletionService, and he needs to provide an Executor as a parameter for constructor. example: Executor Executor = ... CompletionService CS = New ExecutorCompletionService (Executor); Future fs = cs.submit (...); FUTURE FT = CS.Take (); 4. Semaphore The amount of signal is used for synchronous and mutually exclusive low-level primitives. ACQUIRE () and release () operations provided by the semaphore, the same as the P, V on the operating system. example: Buffer: Public class buffer { PRIVATE SEMAPHORE S = NULL; PRIVATE SEMAPHORE P = NULL; Vector Public buffer (int Capacity) { s = new semaphore; P = new semaphore (0); } Public void Put (INT i) { Try { S.acquire (); v.add (new integer (i)); p.Release (); } catch (exception e) { E.PrintStackTrace (); } } Public int GET () { INT i = 0; Try { p.acquire (); i = ((Integer) v.remove (0)). INTVALUE (); S.RELEASE (); } catch (exception e) { E.PrintStackTrace (); } Return I; } } Producer: Public class producer extends thread { Private buffer b; PRIVATE INT COUNT; PRIVATE INT STEP; Private int ID; Public Producer (Buffer B, INT Step, Int ID) { THIS.B = B; THIS.STEP = STEP; THIS.ID = ID; count = 0; } Public void run () { Try { While (true) { System.out.println ("in put"); B.PUT (count); System.out.println ("Producer" ID ":" count); COUNT ; Thread.sleep (STEP); System.out.println ("OUT PUT"); } } catch (exception e) { E.PrintStackTrace (); } } } consumer: Public Class Consumer Extends Thread {Private Buffer B; PRIVATE INT STEP; Private int ID; Public Consumer (Buffer B, Int Step, Int ID) { THIS.B = B; THIS.STEP = STEP; THIS.ID = ID; } Public void run () { Try { While (true) { System.out.println ("in get"); System.out.println ("/ T / TConsume" ID ":" B.Get ()); System.out.println ("Out Get"); Thread.sleep (STEP); } } catch (exception e) { E.PrintStackTrace (); } } } test program: Public class cptest { Public static void main (String [] args) { Buffer b = new buffer (3); Consumer C1 = New Consumer (B, 1000, 1); Consumer C2 = New Consumer (b, 1000, 2); Producter P1 = New Producter (B, 100, 1); Producer P2 = New Producter (B, 100, 2); C1.Start (); C2.Start (); p1.start (); P2.start (); } } 5. CyclicBarrier CyclicBarrier allows a set of threads to wait on a time point, and then continue to execute after all processes reach the waiting point. After CyclicBarrier is used, the CyclicBarrier can be reused by calling the reset () method. The thread reduces the count by calling AWAIT (). Cyclicbarrier example: task: Public class task extends thread { Private string id; Private cyclicbarrier C; Private int Time; Public Task (Cyclicbarrier C, String ID, INT TIME) { THIS.C = C; THIS.ID = ID; this.Time = Time; } Public void run () { Try { System.out.println (ID "start"); Thread.sleep (Time); System.out.println (ID "Finish"); C.AWAIT (); System.out.println (ID "EXIT"); } catch (exception e) { E.PrintStackTrace (); } } } Test class: Public class test { Public static void main (String [] args) { Cyclicbarrier C = New CyclicBarrier (3, New Runnable () { Public void run () { System.out.println ("All Work Done"); } }); Task T1 = New Task (C, "1", 1000); Task T2 = New Task (C, "2", 3000); Task T3 = New Task (C, "3", 5000); T1.Start (); T2.Start (); T3.Start (); } } Output results: 1 Start 2 START 3 Start 1 Finish 2 Finish 3 Finish All Work Done 3 exit 1 exit 2 exit 6. CountDownLatch CountDownLatch has a function similar to the CyclicBarrier and allows a set of threads to synchronize at some point. But unlike CyclicBarrier is: 1.countdownLatch can't be reused, 2. Threads on CountDownLatch, I will be blocked until the count value is 0, and the count value can only be passed through the CONUTDOWN () method Perform reduction. In particular, when the value of countdownlatch is 1, the Latch is called "starting gate", all task threads are on the latch, but until a non-task thread calls countdown () trigger, all task threads start at the same time jobs. 7. Exchanger Exchanger is a CyclicBarrier similar to a count value of 2. She allows two threads to exchange data on a certain point. example: Public class fillandempty { Exchange DataBuffer InitialeemptyBuffer = ... a Made-Up Type DataBuffer InitialFullBuffer = ... Public class fillingloop imports runnable { Public void run () { DataBuffer currentbuffer; = initialemptybuffer; Try { While (currentbuffer! = null) { AddTobuffer (CURRENTBUFFER); CurrentBuffer.Full ()) CurrentBuffer = Exchanger.exchange (CurrentBuffer); } } catch (interruptexception ex) {... handle ...} } } Public Class EmptyingLoop Implements Runnable { Public void run () { DataBuffer CurrentBuffer = InitialFullBuffer; Try { While (currentbuffer! = null) { Takefrombuffer; CURRENTBUFFER CurrentBuffer.empty ()) CurrentBuffer = Exchanger.exchange (CurrentBuffer); } } catch (interruptexception ex) {... handle ...} } } Public void start () { NEW THREAD (New FillingLoop ()). Start (); New Thread (New EmptyingLoop ()). start (); } } EXCHANGE 8. Lock, Condition The lock is the most basic synchronization primitive. By calling the Lock () and UNLOCK () operations on the lock, it can achieve similar effects with the synchronized keyword, but it is important to note that the lock must be explicitly released, and if the abnormality is thrown, no lock is released, Resulting in the deadlock. AWAIT (), Signal (), Signal (), provided by Condition, has similar meanings with the original Wai (), Notify (), NotifyAll () operation. The two main subclasses of Lock are ReentrantLock and Readwritelock. The role of READWRITELOCK is to allow multiple people to read, and one person is written. example: Use Lock and Condition producers, consumer issues Public class boundedbuffer { Final Lock Lock = New ReentrantLock (); Final Condition NotFull = Lock.newcondition (); Final Condition Notempty = LOCK.NEWCONDITION (); Final Object [] Items = New Object [100]; INT PUTPTR, Takeptr, Count Public void Put (Object X) throws interruptedException { LOCK.LOCK (); Try { While (count == items.length) NOTFULL.AWAIT (); Items [PUTPTR] = X; IF ( Putptr == items.length) PUTPTR = 0; COUNT; Notempty.signal (); } finally { Lock.unlock (); } } Public Object take () throws interruptedException { LOCK.LOCK (); Try { While (count == 0) Notempty.await (); Object x = items [takeptr]; IF ( Takeptr == items.length) Takeptr = 0; --count; NOTFULL.SIGNAL (); Return X; } finally { Lock.unlock (); } } } 9. Summary: The new ConcURRENT package provides a synchronization operation from low to high. 10. Annotation Annotation is a new grammar provided by J2SE. According to the specification, his role is simple to simplify the maintenance of code. For example, EJB requires 7 files, an XML file is represented, through Annotation, we can only maintain the source code, and other work can be achieved by automatic generation. This approach is consistent with the effect of Lomboz, but Lomboz is implemented through xDoclet, and now you can use Annotation, but Annotation is just a necessary condition. If you really want to automatically generate other files, in addition to Annotation, Need support for other classes, or tools. Predefined Annotation Tiger is a predefined AnNotation, which is Override, DepRecated, SuppressWarnings, respectively. i. Override1. Run: The role of OVERRIDE is that the method of life Override must be an overlay of the method in the middle of the parent class. If the method does not appear in the parent class, or the method does not correctly override the method in the parent class, the compile period is wrong. 2. Syntax: @Override public void methoda () {...} 3. Example: father: / * * CREATED ON 2005-1-4 * * / Package test; / ** * * @Author cenyongh@mails.gscas.ac.cn * / Public class test { Public test () { } Public void hello () { System.out.Println ("Hello"); } Public void bye () { System.out.println ("BYE"); } } Subclass: / * * CREATED ON 2005-1-5 * * / Package test; / ** * * @Author cenyongh@mails.gscas.ac.cn * / Public Class Overtest Extends Test { @Override public void hello () {} @Override public void methoda () {} } Error message: The method methoda () of Type Overtest Must Override a superclass method 4. Evaluation: With Override, we can ensure that the methods in the subclass have indeed covered methods in the parent class. But now the general IDE may provide this indication that there is a corresponding symbol, indicating whether the method I am using, indicating whether a method covers the method in the parent class, so this tag, or only for those It is also a more significant role in using UltraEdit. Ii. DepRecated Role: Used to declare a method is not recommended. 2. Syntax: @Deprecated public void methoda () {...} 3. Example: Disclaimer: / * * CREATED ON 2005-1-4 * * / / ** * * @Author cenyongh@mails.gscas.ac.cn * / Public class test { Public test () { } / ** * * @DepRecated * * / Public void hello () { System.out.Println ("Hello"); } @Deprecated public void bye () { System.out.println ("BYE"); } } Call class: / * * CREATED ON 2005-1-5 * * / / ** * * @Author cenyongh@mails.gscas.ac.cn * / Public class caltest { Public calltest () { Test T = New Test (); t.hello (); T.bye (); } } Compilation information: Calltest.java: 14: Warning: [DepRecation] Hello () in Test Has Been DepRecated t.hello (); ^ Calltest.java:15: Warning: [DepRecation] BYE () in test has been deprecated T.BYE (); ^ 2 Warnings 4. Evaluation: For deprecated tags, I think that there is already a deprecated in the previous Javadoc tag, why J2SE has to increase this one, completely do not understand. Iii. SuppressWarnings Role: The role of this tag is to allow the compiler to ignore the error of some compile periods, no error. 2. Syntax: @Suppresswarnings ("unchecked") public void void methoda () {...} 3. Example: Original file: Public void bye () { ArrayList List = New ArrayList (); List.add ("Hello"); System.out.println ("BYE"); } Error message: WARNING: [Unchecked] unchecked call to add (e) as a member of the raw type java.util.ArrayList List.add ("Hello"); Modified file: @Suppresswarnings ({"unchecked"}) public void bye () { ArrayList List = New ArrayList (); List.add ("Hello"); System.out.println ("BYE"); } 4. Evaluation: The role of SuppressWarnings is to hide some messages of some compile periods, where he is mainly used or in terms of model. However, in fact, this tag is not implemented in Tiger, so the modified code is in his output result, or it will still output the same error, huh, huh. 2. Customize Annotation Programmers can customize some specific Annotation according to their needs. However, I think it is very important, that is, the existence of Annotation should not affect the semantics of the Java program, that is, before and after using Annotation, the execution should not change, even if a programmer does not understand Annotation The grammar, he should also be able to read Java source code without barrier. I. Syntax: Annotation generally has three forms, which is not containing attributes, only one attribute, and multiple properties. 1. Does not contain attributes: Public @Interface myanno {} Note: The role of Annotation without attributes is similar to the interface that does not contain methods, but is only used as a marker. 2. A property: Public @Interface myanno { String value (); } Note: When only one property is included, the name of the property needs to be named Value, which is a regulation in Annotation. 3. Multiple properties: Public @Interface myanno { String hello (); INT INCOME () Default 1; } Note: When there are multiple properties, the attribute name can be arbitrary. Note that the type of attribute must be basic type, string, enum, clas, annotations, and array of array of these types, and attributes can declare the default values via Default. II. Use: When using the Annotation, it is similar to the declaration (public, private, etc.), but they are all placed in the first One, before public. 1. Does not contain attributes: @MYANNO public void methoda () {...} 2. A property: @MYANNO ("Hello") Pubic Void Methoda () {...} or @MYANNO (value = "hello") public void methoda (...) 3. Multiple properties: @MYANNO (Hello = "Hello", income = 1) public void methoda () {...} Iii. Example: Annotation class: / * * CREATED ON 2005-1-4 * * / Package test; Import java.lang.annotation. *; / ** * * @Author cenyongh@mails.gscas.ac.cn * / @ReTENTION (RETENTIONPOLICY.RUNTIME) Public @Iterface remote {} Use classes: / * * CREATED ON 2005-1-4 * * / Package test; Import java.lang.reflect. *; / ** * * @Author cenyongh@mails.gscas.ac.cn * / Public class test { Public test () {} @Remote Public void Hello () { System.out.Println ("Hello"); } @Remote Public Void Bye () { System.out.println ("BYE"); } Public static void main (String [] args) { Try { Class C = Class.Forname ("Test.Test"); Method [] MS = C.getMethods (); For (Method M: MS) { IF (M.isannotationPresent (transote.class)) { System.out.println (M.GetName ()); } } } catch (exception e) { E.PrintStackTrace (); } } } IV. Note: When declaring a new Annotation, you usually take the @Retrion tag because this indicates the survival time of the Annotation. The value of @ReTention has 3, and retlationPolicy.Source indicates that Annotation is only valid and compiled, and it will be lost after compiling. RetentionPolicy.class indicates that Annotaion will be saved to the .class file, but will not be extracted by the VM. RetentionPolicy.Runtime indicates that Annotaion will be saved in the .class file, and run, it will be extracted by the VM, that is, through the Reflect method, it is possible to obtain the tag. 3. Evaluation: In general, the meaning of Annotation is not as large as the new features such as Enhance for loop, Generic Types mentioned earlier, but this is just relatively, because Annotation does not affect the semantics of Java, so for general Java programmers It is completely ignored. Moreover, if you really want to use Annotation, the programmer also needs to write the code of the Reflecta to extract these Annotations to do additional work. In this general, it should be relatively small. However, Annotation is true for other programmers, and other programmers are indeed useful. When we developed, we can achieve the desired effects without the way of xdoclet.