---------- Android training, Java training, and hope to communicate with you!
----------
1. the static Import statement can be used to import a class or all classes in a package. The import static statement can be used to import a static method or all static methods in a class. Syntax example: Import static Java. lang. math. sin; import static Java. lang. math. *. In this way, you can directly use the static method name in math. 2. variable parameters
Problem: the number of parameters accepted by a method is not fixed, for example:
System. Out. println (countscore (2, 3, 5 ));
System. Out. println (countscore (1, 2, 3, 5 ));
It can only appear at the end of the parameter list. Remember this.
... Is located between the variable type and the variable name. It can be left with or without spaces;
When a variable parameter method is called, the compiler implicitly creates an array for the variable parameter and accesses the variable parameter in the method body as an array.
public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println(add(1,2,3,5));System.out.println(add(2,3,5));}public static int add(int x,int ...args) {int sum = x;for(int i=0;i<args.length;i++) {sum += args[i];}return sum;}3. Enhance the For Loop
Syntax:
For (type variable name: Set variable name ){... }
Note:
Iteration variables must be defined in!
Collection variables can be arrays or collection classes that implement the iterable interface.
Example:
public static int add(int x,int ...args) { int sum = x; for(int arg:args) { sum += arg; } return sum; }4. Automatic packing and unpacking of Basic Data Types
Basic data types (8 types): Boolean, byte, Char, short, Int, long, float, double
Automatic packing:
Integer num1 = 12;
Automatic unpacking:
System. Out. println (num1 + 12 );
The packaging class of basic data has a buffer pool-127-128 except float and double. If data exists in this range, no new objects are created and referenced.
Enjoy the metadata design model flyweight
Many small objects have the same attributes and use the same attributes as an object. Those with different attributes are passed as method parameters, which are called external states, the same as the internal status.
5. Enumeration
Enumeration is generated so that the value of a variable of a certain type can only be one of several fixed values. Otherwise, the compiler reports an error. Enumeration allows the compiler to control the invalid values filled in the source program during compilation. Normal variables cannot be implemented in the development phase.
Simulate enumeration classes using common classes
There can be several public or abstract methods. When nextday is defined using an abstract method, a large number of if. Else statements are transferred into independent classes. Anonymous classes are used to implement the subclass function of abstract classes.
package cn.itcast.day1;public abstract class WeekDay1 {private WeekDay1(){};public final static WeekDay1 SUN= new WeekDay1(){@Overridepublic WeekDay1 nextDay() {// TODO Auto-generated method stubreturn MON;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn "SUN";}};public final static WeekDay1 MON = new WeekDay1(){@Overridepublic WeekDay1 nextDay() {// TODO Auto-generated method stubreturn SUN;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn "MON";}};public abstract WeekDay1 nextDay();public abstract String toString();/*public WeekDay nextDay(){if(this == SUN){return MON;}else{return SUN;}}public String toString(){return this == SUN?"MON":"SUN";}*/}Basic Application of enumeration
Example: Defines the weekday enumeration.
Extension: Values, valueof, name, tostring, ordinal, and other methods of enumeration classes
Valueof can convert a string in a webpage to a Java object
Weekday weekday = weekday. fri; system. out. println (weekday. name (); // Fri restructured the tostring method system by default. out. println (weekday. ordinal (); // The position from 0 that is printed in the enumeration: 5system. out. println (weekday. valueof ("fri"); // you can convert the string in the webpage to the enumerated object system. out. println (weekday. values (). length); // obtain an enumerated Array
Summary: Enumeration is a special class. Each element of this class is an instance object of this class. For example, you can call weekday. sun. getclass (). getname and weekday. class. getname ().
Advanced enumeration applications
Enumeration is equivalent to a class. You can also define constructor, member variables, common methods, and abstract methods.
The enumeration element must be located in the first part of the enumeration body. A semicolon must be placed after the enumeration element list to be separated from other members. Place member methods or variables in enumeration before enumeration elements, and the compiler reports errors.
Enumeration with constructor:
The constructor must be defined as private
If there are multiple constructor methods, how do I select which constructor? () With Parameters
The enumeration elements Mon and Mon () have the same effect. They call the default constructor.
public enum WeekDay{SUN(),MON(1),TUE,WED,THI,FRI,STA;private WeekDay(){System.out.println("null");}private WeekDay(int day){System.out.println(day);}}
Enumeration with methods:
Define enumeration trafficlamp
Implement the common next Method
Implement the abstract next method: each element is an instance object generated by the subclass of the enumeration class, which is defined in a way similar to the internal class.
Add a time representation constructor.
Write the following procedure:
Enumeration steps and tips with abstract methods:
1. enumtrafficlamp {red, green, yellow}
2. enumtrafficlamp {red, green, yellow; public abstract next ();}
3. Enum trafficlamp {red {}, green {}, yellow {}; public abstract next ();}
4. Fill in the next method in each.
public enum Trafficlamp{RED(50){@Overridepublic Trafficlamp nextLamp() {// TODO Auto-generated method stubreturn GREEN;}},YELLOW(5){@Overridepublic Trafficlamp nextLamp() {// TODO Auto-generated method stubreturn RED;}},GREEN(25){@Overridepublic Trafficlamp nextLamp() {// TODO Auto-generated method stubreturn YELLOW;}};public abstract Trafficlamp nextLamp();private int time;private Trafficlamp(int time){this.time = time;};}
Only one member can be enumerated as a singleton implementation method. (See the singleton design mode in this blog)
6. Annotations
An annotation is a class. Creating an annotation is to create a class.
Several Basic annotations provided by Java
@ Suppresswarning ("deprecation ")
Alarm set used to cancel display
@ Deprecated
Program Elements annotated with @ deprecated do not encourage programmers to use such elements because they are dangerous or have better options. The compiler will issue a warning when you use an unsupported program element or execute a rewrite in an unsupported code.
@ Override
Indicates that one method declaration intends to override another method declaration in the superclass. If the method uses this annotation type for annotation but does not overwrite the superclass method, the compiler generates an error message.
Several other common Java annotations
@ Retention indicates how long the comment of the comment type will be retained. If the retention comment does not exist in the annotation type declaration, the retentionpolicy is retentionpolicy. Class by default.
Retentionpolcy Value
Enumerated constant
The class compiler records the annotation in the class file, but the VM does not need to keep the annotation at runtime.
The runtime compiler records the annotation in the class file and retains the annotation when running VN. Therefore, the annotation object can be obtained through reflection.
Comments to be discarded by the source compiler are not kept in the class file.
@ Target indicates the types of elements applicable to the annotation type.
Elementtype [] value
Enumerated constant
Annotation_type annotation type declaration
Constructor Constructor
Field field Declaration (including enumeration constants)
Local_variable local variable Declaration
Method method declaration
Package package Declaration
Parameter parameter Declaration
Type class, interface (including annotation type), or enumeration Declaration
Add basic attributes for annotations
Define the attributes and application attributes of the basic type:
Add string color () to the annotation class ();
@ Myannotation (color = "red ")
Obtain the instance object corresponding to the annotation in reflection mode, and then call the method corresponding to the attribute through this object.
Myannotation A = (myannotation) annotationtest. Class. getannotation (myannotation. Class );
System. Out. println (A. color ());
The above @ myannotation is an instance object of the myannotaion class.
Specify the default value for the property:
String color () Default "yellow ";
Value Attribute:
String Value () Default "zxx ";
If there is an attribute named value in the annotation and you only want to set the value attribute (that is, all other attributes use the default value or you only have one value attribute), you can omit the value = Section. For example: @ myannotation ("lhm ").
Add advanced attributes to an array
Attribute of array type
Int [] arrayattr () default {1, 2, 3 };
@ Myannotation (arrayattr = {2, 3, 4 })
If there is only one element in the array attribute, the attribute value can be omitted.
Enumeration type attributes
Enumtest. trafficlamp lamp ();
@ Myannotation (lamp = enumtest. trafficlamp. Green)
Annotation type attributes:
Metaannotation annotationattr () default @ metaannotation ("XXXX ");
@ Myannotation (annotationattr = @ metaannotation ("YYY "))
You can think that the above @ myannotation is an instance object of the myannotaion class. Similarly, you can think that the above @ metaannotation is an instance object of the metaannotation class. The call code is as follows:
Metaannotation MA = myannotation. annotationattr ();
System. Out. println (MA. Value ());
The detailed syntax of the annotation can be understood through the Java language specification, that is, the Java language specification
Open the j3toc.html page, search for annotation, and enter section 9.6. The 5th discussion section describes the attribute types. You can see that the enumerated attribute types include: basic data type, string, class, enumeration, other annotations, and arrays of these types.
Annotationtest: used for testing
package cn.itcast.day2;@MyAnnotation(arrs={1,2,1,3})public class AnnotationTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubif(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){MyAnnotation myAnnotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);System.out.println(myAnnotation.color());System.out.println(myAnnotation.value());System.out.println(myAnnotation.arrs().length);System.out.println(myAnnotation.annotationArr().age());}}}
Myannotation: annotation created by me
package cn.itcast.day2;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.Method;import java.lang.reflect.Type;@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public @interface MyAnnotation {String color() default "asd";String value() default "yyy";int[] arrs() ;MetaAnnotation annotationArr() default @MetaAnnotation(age=1);}
Metaannotation
package cn.itcast.day2;public @interface MetaAnnotation {String value() default "aaa";int age();}7. Generic
The significance of generics: when defining a set, you need to specify which type of data you want to install to the set, and cannot add data other than the specified type.
Generics are for the javac compiler.
Generics are provided for the javac compiler. They can limit the input type in the set and prevent the compiler from inputting illegal data in the source program, the "type" information will be removed when the compiler compiles a set with the type description, so that the program running efficiency is not affected. For parameterized generic types, getclass () the Return Value of the method is exactly the same as that of the original type. The bytecode generated by compilation removes generic type information. If you can skip the compiler, you can add other types of data to a generic set. For example, you can use reflection to obtain a set, call the add method.
// Use reflection to skip the generic type restriction arraylist <integer> C = new arraylist <integer> (); C. getclass (). getmethod ("add", object. class ). invoke (C, "ABC"); system. out. println (C. get (0); // print the result as ABC
// The Generic Model removes the "type" information during compilation. Vector <integer> Vi = new vector <integer> (); vector <string> Vs = new vector <string> (); system. out. println (VI. getclass () =. getclass (); // The result is true.
In-depth understanding of generics
Arraylist <E> class definition and arraylist <integer> class reference involve the following terms:
This is called the arraylist <E> generic type.
E In arraylist <E> is called a type variable or a type parameter.
The entire arraylist <integer> is called a parameterized type.
An integer in arraylist <integer> is an instance of the type parameter or an actual type parameter.
In arraylist <integer>, <> Read typeof
Arraylist is called the original type.
Compatibility between parameterized types and original types:
A parameterized type can reference an object of the original type and compile a report warning, for example,
Collection <string> C = new vector (); // is it true? Isn't it a single sentence for the compiler?
The original type can reference an object of the parameterized type and compile the report warning, for example,
Collection c = new vector <string> (); // the original method accepts a set parameter, and the new type must be passed in.
Parameterized types do not consider the inheritance relationship of type parameters:
Vector <string> V = new vector <Object> (); // error! /// Do not write <Object> yes. If you write it, it is a known object.
Vector <Object> V = new vector <string> (); // error!
The compiler cannot create arrays of generic variables. That is, when creating an array instance, the array elements cannot use parameterized types. For example, the following statement has an error:
Vector <integer> vectorlist [] = new vector <integer> [10];
Question: Will the following code report an error?
Vector V1 = new vector <string> ();
Vector <Object> V = V1;
// Compiled
In generics? Wildcard
Use? Wildcards can reference other parameterized types ,? Variables defined by Wildcards are mainly used as references. You can call Methods unrelated to parameterization, rather than methods related to parameterization.
Example: collection <?> A can match any parameterized type, but only later will know what type is matched,
A = new arraylist <integer> and A = new arraylist <string> can be used, but neither a. Add (new date () nor a. Add ("ABC") can be used,
Limit the upper boundary of a wildcard:
Correct: vector <? Extends number> X = new vector <integer> ();
Error: vector <? Extends number> X = new vector <string> ();
Limit the bottom boundary of a wildcard:
Correct: vector <? Super integer> X = new vector <number> ();
Error: vector <? Super integer> X = new vector <byte> ();
Only the reference type can be used as the actual parameter of the generic method.
Swap (New int [] {}, 3,5); // swap (New String [] {}, 3,5 ); // correct public static <E> void swap (E [] A, int I, Int J) {e temp = A [I]; A [I] = A [J]; A [J] = temp ;}Determining the type of a type parameter
The process for the compiler to determine the actual type parameter of the model method is called type inference. The type inference is relative to perceptual inference, and its implementation method is a very complicated process.
The rule is as follows:
When a type variable is only applied to one of all parameters and return values in the entire parameter list, it is determined based on the actual application type at the time of calling the method, this is easily inferred by feeling, that is, the type of the generic parameter is directly determined based on the type or return value of the parameter passed when the method is called. For example:
Swap (New String [3], 3,4) à static <E> void swap (E [] A, int I, Int J)
When a type variable is applied to multiple parameters and return values in the entire parameter list, if the actual application types in multiple parameters correspond to the same type when calling the method, this is easily inferred by feeling, for example:
Add (3, 5) à static <t> t add (t a, t B)
When a type variable is applied in multiple places of all parameters and return values in the entire parameter list, if the actual application types in multiple places correspond to different types when the method is called, and no return value is used, at this time, the maximum intersection type among multiple parameters is obtained. For example, the actual type of the following statement is number. Compilation is okay, but there is a problem during running:
Fill (new integer [3], 3.5f) à static <t> void fill (T [] A, t v)
When a type variable is applied in multiple places of all parameters and return values in the entire parameter list, if the actual application types in multiple places correspond to different types when the method is called, and the return value is used, at this time, the type of the returned value is given priority. For example, if the actual type of the following statement is integer, an error will be reported during compilation. Change the type of variable X to float, and compare the error message reported by eclipse, then, change the X type of the variable to number. The error is not returned:
Int x = (3, 3.5f) à static <t> t add (t a, t B)
The type inference of the parameter type is passed. In the first case below, it is inferred that the actual parameter type is object, and there is no problem in compilation, in the second case, the type variable is directly determined as the string type based on the parameterized Vector class instance, and the compilation will fail:
Copy (new integer [5], new string [5]) à static <t> void copy (T [] A, T [] B );
Copy (new vector <string> (), new integer [5]) à static <t> void copy (collection <t> A, T [] B );
Define generic classes
public class GenericDao<T> {private T field1;public void save(T obj){}public T getById(int id){}}
Note:
When you parameterize a generic type, the instance of the type parameter must be a reference type, not a basic type.
When a variable is declared as a generic type, it can only be called by instance variables, methods, and internal classes, rather than static variables and static methods. Because static members are shared by all parameterized classes, static members should not have class-level parameters.
Obtain generic parameterized types through reflection (difficult)
Method methodApply = GenericTest.class.getDeclaredMethod("applyGeneric", Vector.class);Type[] paramTypes = methodApply.getGenericParameterTypes();ParameterizedType param = (ParameterizedType)(paramTypes[0]);System.out.println(param.getRawType());System.out.println(param.getActualTypeArguments()[0]);System.out.println(((Class)param.getRawType()).getName() + "<" + ((Class)param.getActualTypeArguments()[0]).getName()+ ">");public static void applyGeneric(Vector<String> v){}Exercise 1 of the generic method: compile a generic method to automatically convert objects of the object type to other types. 2. Define a method to fill all elements in an array of any type into an object of the corresponding type. 3. Use a custom generic method to print all content in a set of any parameter types. In this case, the preceding wildcard scheme is more effective than the normal method. When a type variable is used to express the relationship between two parameters or between parameters and return values, that is, the same type variable is used in the method signature, or the type variable is also used in the method body code, rather than only used in the signature. 4. Define a method to securely copy data from a set of any parameter types to an array of the corresponding type. 5. Define a method to securely copy data from an array of any parameter type to another array of the corresponding type.
1. public static <t> T autoconverttype (Object OBJ) {return (t) OBJ;} test code: Object xxx = "ABC"; string YYY = autoconverttype (XXX ); another common application of the generic method is that the caller does not need to convert the type of the returned value. We recommend that you check the basedao code in the Baba sports video of Chuanzhi podcast. 2. public static <t> T [] fill (T [] A, t v) {for (INT I = 0; I <. length; I ++) A [I] = V; return a;} 3. public static <E> void printcollection (collection <E> Cols) {for (e OBJ: Cols) {system. out. println (OBJ) ;}} 4. the generic method must be used for definition. If the following form is used: static void copy (collection A, object [] B ); otherwise, data of type A may be copied to an array of type B. The generic method is defined as static <t> void copy (collection <t> A, T [] B );
8. Lock and condition
/* After jdk1.5, the synchronization and lock will be encapsulated into an object. The operation lock is implicitly defined in this object, and the implicit action is changed to the display action. Lock interface: the synchronous code block or function is replaced. Converts the synchronous implicit Lock operation into a real lock operation. At the same time, it is more flexible. Multiple sets of monitors can be added to one lock. Lock (): Get the lock. Unlock (): Release the lock, which usually needs to be defined in the finally code block. Condition interface: Replace the wait policy policyall method in the object. These monitor methods are encapsulated separately and become the condition monitor object. Any lock can be combined. Await (); signal (); signalall (); */import Java. util. concurrent. locks. *; Class resource {private string name; private int COUNT = 1; private Boolean flag = false; // create a lock object. Lock = new reentrantlock (); // obtain the monitor object of the lock through an existing lock. // Condition con = lock. newcondition (); // two sets of monitors are obtained through an existing lock, one for monitoring producers and the other for monitoring consumers. Condition producer_con = lock. newcondition (); condition consumer_con = lock. newcondition (); Public void set (string name) // t0 T1 {lock. lock (); try {While (FLAG) // try {lock. wait ();} catch (interruptedexception e) {}// T1 t0try {producer_con.await ();} catch (interruptedexception e) {}// T1 t0this. name = Name + count; // roast duck 1 roast duck 2 roast duck 3 count ++; // 2 3 4system. out. println (thread. currentthread (). getname () + "... producer 5. 0... "+ this. Name); // produce roast duck 1 produce roast duck 2 produce roast duck 3 flag = true; // notifyall (); // con. signalall (); consumer_con.signal () ;}finally {lock. unlock () ;}} public void out () // T2 T3 {lock. lock (); try {While (! Flag) // try {This. wait ();} catch (interruptedexception e) {}// T2 t3try {cousumer_con.await ();} catch (interruptedexception e) {}// T2 t3system. out. println (thread. currentthread (). getname () + "... consumer. 5. 0 ....... "+ this. name); // consume roast duck 1 flag = false; // yyall (); // con. signalall (); producer_con.signal ();} finally {lock. unlock () ;}} class producer implements runnable {private resource R; Producer (resource R) {This. R = r;} public void run () {While (true) {R. set ("roast duck") ;}} class Consumer implements runnable {private resource R; Consumer (resource R) {This. R = r;} public void run () {While (true) {R. out () ;}} class producerconsumerdemo2 {public static void main (string [] ARGs) {resource r = new resource (); Producer pro = new producer (R ); consumer con = new consumer (r); thread T0 = new thread (Pro); thread T1 = new thread (Pro); thread t2 = new thread (CON ); thread T3 = new thread (CON); t0.start (); t1.start (); t2.start (); t3.start ();}}
---------- Android training, Java training, and hope to communicate with you!
----------
See http://edu.csdn.net/heima/ for details