Java programming notes 19 Java advanced features

Source: Internet
Author: User

1. Automatic packing and unpacking

Automatic Packing refers to encapsulating basic data types into class objects, and unpacking refers to splitting class objects into basic data types.

For example, the following code can be compiled after Java 5.0.

// Automatically boxed integer in = 3; short SH = 2; long Lo = 3l; double DBL = 3.4d; float FL = 1.2f; byte bt = 12; character CHT = 'C'; // automatic unpacking int I = new INTEGER (3); short S = new short (short) 1 ); long L = new long (3l); double D = new double (2.3d); float F = new float (1.2f); byte B = new byte (byte) 23 ); char CH = new character ('A ');

However, Java didn't work before, because the data types on both sides are different. One is the basic data type and the other is the object. You must call the Wrapper class method to convert the object and the basic data type.

The packaging class is not described here.

2. New for/in loop,

You only need to specify the element type to be traversed in the for loop and the object to be traversed:

Package COM. book. ch10.java5; import Java. util. arraylist; import Java. util. list; public class jforinarray {public static void main (string [] ARGs) {string [] array = {"A", "B", "C", "D "}; for (string S: array) {system. out. println ("traversal array:" + S) ;}list <string> List = new arraylist <string> (); list. add ("A"); list. add ("B"); list. add ("C"); list. add ("D"); For (string OBJ: List) {system. out. println ("traversal set:" + OBJ );}}}

3. Variable Length Parameter Method

To define a variable length parameter, add a ellipsis after the parameter type, and then add the variable length parameter name. Variable Length parameters are represented as arrays in the method. You can use arrays in the traditional array traversal mode, or use the new for/in loop:

Package COM. book. ch10.java5; public class jvararstest {public static double AVG (double... values) {// Variable Length Parameter definition method double Total = 0; int COUNT = values. length; For (double I: values) {// use total + = I;} return total/count;} public static void main (string [] ARGs) for Variable Length Parameters) {system. out. printf ("the average is % S. % N ", AVG (3, 4.2, 2); system. out. printf ("the average is % S. % N ", AVG (); system. out. printf ("the average is % S. % N ", AVG (New Double [] {3, 4.2, 2 }));}}

4. covariant return type

It is allowed to make the return value of the parent class method more specific when overwriting the parent class method. For example, the get (INT index) of the arraylist class returns an object. After inheriting the arraylist class, you can override the get method and change the returned value to string, because string is also a subclass of the object. Before Java, this is not allowed.

Package COM. book. ch10.java5; import Java. util. arraylist; import Java. util. list; @ suppresswarnings (value = "serial") public class jcovariantreturntypestest extends arraylist {@ override // override methods in the parent class, before 5.0, Public String get (INT index) {return (string) super. get (INDEX);} public static void main (string... ARGs) {jcovariantreturntypestest list = new jcovariantreturntypestest (); list. add ("string"); // you can directly return the string type instead of the objectstring result = List in the parent class. get (0); system. out. printf ("% s", result );}}

5. Static Import

That is, the impot static command imports static methods and static variables of a class. You can directly use the variable name and method name when using the impot static command, instead of adding "Class Name.

Package COM. book. ch10.java5; // The static import variable import static Java. lang. math. pi; // static import method import static Java. lang. math. sin; // statically import all methods and variables import static Java. lang. math. *; public class jstaticimporttest {public static void main (string [] ARGs) {// use methods and variables directly without the math prefix system. out. printf ("Sin (% S) = % S % N", PI, sin (PI); system. out. printf ("cos (% S) = % S % N", PI, cos (PI ));}}

6. Generic

Here, we will only introduce the most basic syntax, which will be detailed later.

Classes and methods can be generic, while generics avoid some runtime errors, so that many errors can be found in the compilation phase.

The class-wide arraylist <E> indicates that the data type stored by arraylist is E, and the E-type represents a class.

The method generic public e get (INT index) indicates that the return value of the method is type E.

Let's look at an example:

Package COM. book. ch10.java5; import Java. util. arraylist; import Java. util. date; import Java. util. list; public class jgenerictest {public static void main (string [] ARGs) {// The parameter type is limited to date type list <date> List = new arraylist <date> (); list. add (new date (); list. add (new date (); list. add (new date (); // classcast is not required. date = List. get (0); system. out. printf ("% S % N", date); For (date DD: List) {system. out. printf ("For/in loop: % 1 $ Tf % 1 $ TT % N", DD );}}}

Note that generic programming can only use classes and cannot use basic types.

An example of using multiple generics in a collection:

Package COM. book. ch10.java5; import Java. util. date; import Java. util. hashmap; import Java. util. map; public class jhashmapgeneric {public static void main (string [] ARGs) {Map <string, date> map = new hashmap <string, date> (); // multiple generic maps. put ("time_1", new date (); map. put ("time_2", new date (); map. put ("time_3", new date (); For (string key: map. keyset () {date = map. get (key); system. out. printf ("key: % 1 $ S, value: % 2 $ Tf % 2 $ TT % N", key, date );}}}

Let's take a look at the wildcard: The wildcard can only be used for type security checks, but cannot be used to declare a specific generic type.

<?> Represents any type, but is used separately? It is basically useless (a single? That is, do not use generics). It is generally used with extends and super.

<?> Together with extends, it indicates the specified type and all its subclasses.

<?> Together with super, it indicates the specified type and all its parent classes.

Because wildcards can only perform type security checks and cannot be used to declare a specific generic class, the following usage is incorrect.

List <?> = New arraylist <?> // Cannot be used for declaration

Let's look at an example of using wildcards for type check:

Package COM. book. ch10.java5; import Java. util. arraylist; import Java. util. date; import Java. util. list; public class jwildcard {// The list accepted by the wildcard can be number and its subclass public static void numberlist (list <? Extends number> List) {for (number num: List) {system. out. printf ("output number: % 1 $ S % N", num) ;}// same as public static void datelist (list <? Extends date> List) {for (Date: List) {system. out. printf ("output Date: % 1 $ Tf % 1 $ TT % N", date) ;}} public static void main (string [] ARGs) {list <date> datelist = new arraylist <date> (); // type declaration use a specific generic list <integer> intlist = new arraylist <integer> (); datelist. add (new date (); datelist. add (new date (); intlist. add (3); intlist. add (6); numberlist (intlist); datelist (datelist );}}

A generic class defines the generic type after the class name. A generic method must define the generic type before the return type of the Method Name: write a wildcard:

Package COM. book. ch10.java5; import Java. util. date; public class jgenericmethod {// standardized class. after the class name, use <> to define the fan type T. static Class A <t> {// After definition, use t to directly use the public t generic (t) {return t ;}} static Class B {// normalization method. before returning a method type, use <> define the tpublic type <t> T generic (t) {return t;} // normalization method. use <> define the type T before the return type of the method. This type can only be date and its subclass Public <t extends date> T genericdate (t) {return t ;}} public static void main (string [] ARGs) {A <string> A = new A <string> (); string Ss =. generic ("A string"); B = new B (); string ss2 = B. generic ("another string"); Date = B. genericdate (new date ());}}

7. Enumeration type

The enumeration type cannot be declared inside the method, but can only be declared as a class variable,

Public Enum sex {male, femal, unknow };

Enumeration type Reed variables are real objects and can be viewed as static, final, and public objects.

Package COM. book. ch10.java5; public class jenumeration {public static Enum sex {male, female, unkown,}; public static void main (string [] ARGs) {system. out. printf ("sex. female. tostring (): \ t % S % N ", sex. female. tostring (); system. out. printf ("sex. female. ordinal (): \ t % S % N ", sex. female. ordinal (); system. out. printf ("sex. female. getclass (): \ t % S % N ", sex. female. getclass (); system. out. printf ("% N traverse all sex enumeration variables:"); For (sex: sex. values () {system. out. printf ("% s,", sex);} switch (sex. female) {Case male: // do somethingbreak; Case female: // do somethingbreak; Case unkown: // do somethingbreak; default: // do something }}}

Let's take a look at the extended Enumeration type. Enum is an object like class and interface. Therefore, it can be expanded to add attributes or methods. Like interface constructors, Enum has some limitations:

Enum can have constructor, but cannot have public constructor.

Enum built-in objects must be separated by commas. After declaring all built-in objects, end with semicolons.

The enum built-in object must use the declared constructor; otherwise, the compilation is incorrect.

Let's look at an example:

Package com. Book. ch10.java5; public class jenumtest {static Enum type {// the built-in Enumeration type objects are separated by commas. Manager ("manager", 10000), Assistant ("assistant", 6000), worker ("employee", 4000 ),; // end with a semicolon // extended attribute private string name; private double pay; // The constructor cannot be public type (string name, double pay) {This. name = Name; this. pay = pay ;}} static class person {public person (string name, type) {// note the person type.
This. name = Name; this. type = type;} private string name; private type; Public String getname () {return name;} public void setname (string name) {This. name = Name;} public type GetType () {return type;} public void settype (type) {This. type = type ;}} public static void printinfo (person) {system. out. printf ("Name: % 1 $ S, \ t occupation: % 2 $ S, \ t position salary: % 3 $ S % N", person. getname (), person. getType (). name, person. getType (). pay);} public static void main (string [] ARGs) {person p1 = new person ("James", type. manager); person P2 = new person ("Li Si", type. worker); person P3 = new person ("Wang Wu", type. assistant); printinfo (P1); printinfo (P2); printinfo (P3 );}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.