Dark Horse Programmer -- [Java high-tech] -- New Features of JDK1.5: static import, variable parameters, enhanced for loop, automatic packing and unpacking, enumeration, and new features of jdk1.5

Source: Internet
Author: User

Dark Horse Programmer -- [Java high-tech] -- New Features of JDK1.5: static import, variable parameters, enhanced for loop, automatic packing and unpacking, enumeration, and new features of jdk1.5

I. Static Import

1. Differences between import and import static:

(1) import is to import a class or all classes in a package.

(2) import static is to import a static method or all static methods in a class.

Note: when calling the static method of the static imported class, you do not need to write the class name. For example, Arrays. sort (int []) can directly write sort (int []);

2. Static Import Statement:

(1) import static java. util. Arrays. *; indicates importing all static members in the Arrays class.

(2) import static java. lang. System. *; indicates to import all static members in the System class.

3. Static import considerations:

(1) When two imported classes have members of the same name, you must add the corresponding class name before the Members.

(2) When the class name is duplicate, you must specify the specific package name.

(3) When the method is named again, you must specify the object or class to which the method belongs.

Ii. variable parameters

1. Why are variable parameters introduced?

If a method is used to input multiple parameters in the parameter list and the number of parameters is unknown, the method must be reloaded each time. The code is too repetitive. Although an array can be used as a form parameter, an array object needs to be defined every time when passing data to the form parameter. Therefore, after JDK, a new feature is provided: variable parameters.

2. Variable Parameter writing format:

Add three points between the variable type of the formal parameter and the variable name... , With or without spaces. For example:

Add (int... X ){};

3. Variable Parameter features:

(1) variable parameters must be defined at the end of the parameter list;

(2 )... It is located between "variable type" and "variable name;

(3) A variable parameter is simply an array parameter. The Compiler implicitly creates an array for the variable parameter and accesses the variable parameter in the method body as an array.

Iii. EnhancedLoop

1. format:

For (data type variable name: The retrieved collection or array) {execution statement}

2. Description

(1) traverse the set. Only collection elements can be obtained. However, the set cannot be operated. It can be seen as a short form of iterator.

(2) In addition to traversing, The iterator can also remove elements from the set. If you use ListIterator, you can add, delete, modify, and query the set during the traversal process.

(3) modifiers can be added before the variable type of the enhanced for loop, such as final (accessible by local internal classes ).

3. Differences between traditional for and advanced:

(1) the traditional for loop can perform multiple operations on statements because it can control the increment conditions of the loop. There is a badge index when traversing the array.

(2) An advanced for loop is a simplified form. It must have a traversal target. The target is either a single column set of array or Collection and cannot be traversed directly, however, you can convert a Map Set into a single Set. For example:

1 for( Map.Entry<Integer , String>) me : map.entrySet()){2 3        Integer key = me.getKey();4 5        String value = me.getValue();6 7        System.out.println(key + “::” +value);8 9 }

Iv. Automatic unpacking and packing of Basic Data Types

1. Automatic packing: Integer iObj = 3;

2. Automatic unpacking: iObj + 2;

3. Description of basic data types: the integer ranges from-128 ~ The number between 127 is packaged as an Integer object, which is stored in the cache of the constant pool. when an object is created, if its value is within this range, it is directly searched in the constant pool, because these small values are frequently used, it is much easier to cache them into the constant pool.

4. flyweight ):

Description: there are many small objects with the same attributes. The same attributes are converted into an object. These identical attributes are called the internal state (intrinsic) of the object ). The parameters that convert different attributes into methods are called external States (extrinsic ). This optimized memory mode creates only one object, which is called the metadata mode.

For example, the value range of an Integer object is-128 ~ 127, the objects with the same value are the same, because these small numbers are frequently called, so they are cached in a pool for call at any time. In this way, you do not need to create new objects. This is a typical metadata-sharing design model.

V. Enumeration

(1) Overview

1. enumeration: To make a variable of a certain type have only 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. It is a new feature added in java1.5.

2. Use a common class to simulate the implementation principle of enumeration. Sample Code:

1/* a common class defines a Weekday class to simulate the enumeration function. 2 3 1. private constructor 4 5 2. Each element uses a public static member variable to represent 6 7 3. There may 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. 8 9 */10 11 public abstract class WeekDay {12 13 // The constructor is privatized. Do not allow others to create the object 14 15 private WeekDay () {} 16 17 // Add each element, static constant 18 19 public final static WeekDay SUN = new WeekDay () {20 21 public WeekDay nextDay () {22 23 return MON; 24 25} 26 27 }; 28 29 public final static WeekDay MON = new WeekDay () {30 31 public WeekDay nextDay () {32 33 return SUN; 34 35} 36 37 }; 38 39 public abstract WeekDay nextDay (); 40 41 public St Ring toString () {42 43 return this = SUN? "SUM": "MON"; 44 45} 46 47}

(2) Basic Application of enumeration

1, Overview

(1) Use the enum keyword to define an enumeration class. An enumeration class is a special class, and each element is an instance object of this class.

(2) Use the enumeration class to specify the value, as shown in the preceding WeekDay class. The values defined with this type can only be defined in this class. If these values are not defined, the compiler will not pass.

(3) errors will be found during compilation, reducing errors during runtime.

(4) If the caller wants to print information about the elements in the enumeration class, the caller must define the toString method.

Note: An enumeration class is a class and a final class that cannot be inherited. Its elements are static constants of the class.

2Common enumeration methods

(1) Constructor

① Constructor, called only when constructing enumeration values.

② The constructor is only private and not public. In this way, instance objects cannot be defined externally. The enumerated value is a constant of public static final. The methods and data fields of enumeration classes can be accessed externally.

③ Constructor can have multiple constructor values.

(2) Static Method

① ValueOf (String e): Convert the String to the corresponding enumerated object, that is, convert the String to the object

② Values (): obtains all enumeration object elements.

(3) Non-static method

① String toString (): returns the name of the enumerated quantity.

② Int ordinal (): return the order of the enumerated values in the enumeration class, in the defined order

③ Class getClass (): obtains the corresponding Class name.

④ String name (): returns the name of this enumeration constant and declares it in its enumeration declaration.

3Sample Code:

1 public class EnumDemo {2 3 public static void main (String [] args) {4 5 WeekDay weekday = WeekDay. MON; 6 7 System. out. println ("1" + weekDay); // The output enumerated constant name is 8 9 System. out. println ("2" + weekDay. name (); // name of the output object 10 11 System. out. println ("3" + weekDay. getClass (); // output the corresponding class 12 13 System. out. println ("4" + weekDay. toString (); // name of the output enumerated object 14 15 System. out. println ("5" + weekDay. ordinal (); // output this object in the enumerated constant Order 16 17 System. out. print Ln ("6" + WeekDay. valueOf ("WED"); // converts a string to an enumerated constant 18 19 System. out. println ("7" + WeekDay. values (). length); // obtain the enumerated elements and print them 20 21} 22 23 // define the enumeration class 24 25 public enum WeekDay {26 27 SUN (1 ), MON, TUE, WED, THI, FRI, SAT; // semicolons are optional. However, if there are methods or other members, the semicolon cannot be saved. If there are other methods, they must be under these enumerated variables. 28 29 30 31 // No parameter constructor 32 33 private WeekDay () {34 35 System. out. println ("First"); 36 37} 38 39 // parameter-based constructor 40 41 private WeekDay (int day) {42 43 System. out. println ("Second"); 44 45} 46 47} 48 49}

(3) Advanced enumeration applications

1, Enumeration: It is equivalent to a class. You can also define constructor, member variables, common methods, and abstract methods.

2, Enumeration Element: It must be located at the beginning of the enumeration body. The names of the enumerated elements must be separated by semicolons. Place member methods or variables in enumeration before enumeration elements, and the compiler reports errors.

3, Enumeration with Constructor

(1) The constructor must be defined as "private".

(2) How do I select multiple constructor methods?

(3) The enumeration elements MON and MON () have the same effect. They call the default constructor.

4, Enumeration with methods

(1) define enumeration TrafficLamp

(2) implement the common next Method

(3) 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.

(4) Add a time representation Constructor

*Sample Code:

1 public class EnumTest {2 3 public enum TrafficLamp {4 5 RED (30) {6 7 public TrafficLamp nextLamp () {8 9 return GREEN; 10 11} 12 13 }, 14 15 GREEN (30) {16 17 public TrafficLamp nextLamp () {18 19 return YELLOW; 20 21} 22 23}, 24 25 YELLOW (5) {26 27 public TrafficLamp nextLamp () {28 29 return RED; 30 31} 32 33}; 34 35 private int time; 36 37 // constructor 38 39 private TrafficLamp (int time) {40 41 this. time = time;} 42 43 // abstract method 44 45 public abstract TrafficLamp nextLamp (); 46 47} 48 49}

 


Who will introduce me to some new features after jdk15?

One important topic of "JDK1.5" is to simplify development by adding some features, including generic, for-else loop, automatic package installation/unpacking, and enumeration, variable Parameter, static import. Using these features helps us write code that is clearer, lean, and secure.

Next we will briefly introduce these new features.

1. Generic (Generic)

C ++ can specify the element type of the set through the template technology, while Java has never had the corresponding function before 1.5. An object of any type can be put in a set. When we take objects from the set, we have to forcibly convert them. Tigers introduce generics, which allow you to specify the element types in the set, so that you can get the benefit of checking strong types at compile time.

Collection <String> c = new ArrayList ();
C. add (new Date ());

The compiler will give an error:

Add (java. lang. String) in java. util. Collection <java. lang. String> cannot be applied to (java. util. Date)

2. For-Each loop

The For-Each loop must be added to simplify the traversal of the set. Suppose we want to traverse a set to process the elements. The typical code is:

Void processAll (Collection c ){
For (Iterator I = c. iterator (); I. hasNext ();){
MyClass myObject = (MyClass) I. next ();
MyObject. process ();
}
}

With the For-Each loop, we can rewrite the code:

Void processAll (Collection <MyClass> c ){
For (MyClass myObject: c)
MyObject. process ();
}

This code is much clearer than above and avoids forced type conversion.
3. Autoboxing/unboxing)

Automatic package installation/unpacking greatly facilitates the use of basic data and their packaging.

Automatic package installation: the basic type is automatically converted to the packaging class. (int> Integer)

Automatic package Splitting: the package type is automatically converted to the basic type. (Integer> int)

Before JDK1.5, we always worried that the set cannot store basic types. Now the automatic conversion mechanism solves our problem.

Int a = 3;
Collection c = new ArrayList ();
C. add (a); // It is automatically converted to Integer.

Integer B = new Integer (2 );
C. add (B + 2 );

Here, Integer is automatically converted to int for addition, and then int is converted to Integer again.

4. enumeration (Enums)

JDK1.5 adds a brand new type of "class"-Enumeration type. Therefore, JDK1.5 introduces a new keyword enmu. We can define an enumeration type in this way.

Public enum Color
{
Red,
White,
Blue
}

Then we can use Color myColor = Color. Red.

The enumeration type also provides two useful static methods: values () and valueOf (). We can easily use them, for example

F... the remaining full text>

What are the new features of JDK15?

New features in jdk5.0
Generic)
Enhanced "for" loop (Enhanced For loop)
Autoboxing/unboxing)
Type safe enums)
Static import)
Variable parameters (Var args)

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.