Enhanced JavaSE Basics

Source: Internet
Author: User

Enhanced JavaSE Basics

 

In the course of learning JavaSE, some knowledge needs to be mastered and understood. Next we will strengthen and consolidate the relevant knowledge.

 

I. New Features of JDK 5.0

 

An important topic of JDK 5.0 is to simplify development by adding some features, including:

• Static Import

• Automatic package installation/unpacking

• For-each loop

• Variable parameters

• Enumeration

• Generic

• Metadata

Using these features helps you write code that is clearer, lean, and secure.

 

 

Static Import

 

The static import syntax added by JDK 1.5 is used to import a static property value (method) or all static property values (methods) of a specified class)

 

Syntax:

• Import static package name. Class Name. static attribute | static method | *

Use the import static statement for static import statements

• Import a single static attribute of a specified class:

Import static java. lang. System. out

• Import static methods of specified classes
Import static java. lang. Math. max

• Import all static attributes and methods of the specified class

Import static java. lang. Math .*

 

Automatic packing/unpacking

Autoboxing: assigns a basic data type to the corresponding packaging variable or the Object variable.

 

Automatic unpacking: The packaging class object is directly assigned to a corresponding basic type variable.


Typical applications:

List list = new ArrayList ();

List. add (1 );

Int j = (Integer) list. get (0 );

 

 

Enhance the for Loop

The reason for introducing an enhanced for loop: In versions earlier than JDK5, to traverse elements in an array or set, you must first obtain the array length or set iterator, Which is troublesome!

 

Therefore, JDK 5 defines a new syntax-enhance the for loop to simplify such operations. An enhanced for loop can only be used in an array or a collection class that implements the Iterator interface.

When you use foreach to traverse arrays and set elements cyclically, you do not need to obtain the array and set length.

 

Access to array elements and set elements. The foreach loop automatically traverses each element of the array and set.

 

Syntax format:

For (type variable name: Set variable name ){... }

For (type varName: array | collection ){

// VarName automatically iterates to access each element

}

Examples of using an enhanced for loop:

 

 

 

 

Notes for using an enhanced for loop:

 

 


Introduction: define a method to evaluate the sum of elements in the array


Variable parameters

 

Beginning with JDK 1.5, Java allows you to define parameters with variable length, so that you can specify an uncertain number of parameters for the method.

 

When defining a method, add three points after the type of the last parameter (..., ... Is located between the variable type and the variable name, whether there are spaces before and after) indicates that the form parameter can accept multiple parameter values, multiple parameter values are passed as Arrays

 

A variable parameter can only be placed at the end of the parameter list. Therefore, a method can have at most one variable-length parameter.

 

When you call a method that contains a variable parameter, You can input multiple parameters or an array for the parameter.

 

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.

 

 

Sample Code 1 of the Variable Parameter Method


Sample Code 2 of the Variable Parameter Method


Variable Parameter Method example code 3


Sample Code 4 of the Variable Parameter Method

 

Test the Arrays. asList () method of the class with variable parameters in JDK. Passing multiple parameters and passing arrays respectively

Note: The problem of passing in an array of basic data types.

 

Enumeration class

Why do I need enumeration?

Some methods do not require any data during running, but must be a value within a certain range. This type of problem was solved by using a custom class with enumeration function before jdk5, after Java 5, you can use enumeration to solve the problem.

 

The New enum keyword in JDK 5 is used to define an enumeration class.

 

Enumeration class Introduction

 

Enumeration exercises

Design a Student class

Class Student {

Private String name;

Private Grade grade;

......}

Requirement: the grade of a student can only be a, B, c, d, and e. You can set scores for students and output their scores (excellent, good, medium, acceptable, and poor)

 

 


Manual Implementation of enumeration classes:

• Use private to hide the constructor

• Use public static final to modify all possible instances of this class

• Attributes cannot be modified. Therefore, privatefinal should be used for modification.

 

 


Enumeration class

 

The above writing is quite troublesome. java provides a more convenient method-enumeration class can solve the above problems.

 

The enum keyword added in JDK 1.5 is used to define enumeration classes.

 

Enumeration classes are also special Java classes.

 

Differences between enumeration classes and common classes:

• The enumeration class defined by enum inherits the java. lang. Enum class by default.

• The constructors of enumeration classes can only use private access controllers

• All instances of the enumeration class must be explicitly listed (, separated; ended) in the enumeration class. The listed instance system will automatically add public static final Modification

 

JDK 5 extends the switch statement, which can receive int, byte, char, short, and an enumeration type.

 

If the enumeration has only one member, it can be used as a singleton mode.

 

Enumeration Class 1 (constructor without parameters)

 


Enumeration class attributes

 

Attributes of enumeration objects should not be modified, so private final should be used for modification.

 

The Attribute Modified by the enumeration class using private final should be assigned to it in the constructor.

 

If the enumeration class explicitly defines a constructor with parameters, the corresponding input parameters must also be used to list enumeration values.

Enumeration type 2 (Construction Method with parameters)

 

 

 

 

Enumeration Class 3 (use internal class)

 

 

 


Common enumeration methods

 

The enumerated classes declared in Java are all children of the java. lang. Enum class and inherit all methods of the Enum class. Common Methods:

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

• Ordinal (): returns the ordinal number of the enumerated constant (it is in the enumeration declaration position, where the ordinal number of the initial constant is zero ).

• Valueof (Class enumClass, Stringname): return an enumeration constant of the specified enumeration type with the specified name. Static Method

• Values () This method is not found in the JDK documentation, but each enumeration class has this method, which is very convenient to traverse all enumeration values of the enumeration class.

 


Enumeration exercises

Exercise: compile an enumeration WeekDay for the day of the week. Requirements:

• Enumerated values: Mon, Tue, Wed, Thu, Fri, Sat, and Sun

• This enumeration requires a method to call which returns the week in Chinese format.

 

 

Package net. csdn. time;

// It is an entity Bean about the employee's weekly working hours

Class TimeBean {

PrivateString name;

PrivateWeekDay timeLong;

 

PublicString getName (){

Returnname;

}

Publicvoid setName (String name ){

This. name = name;

}

Public WeekDaygetTimeLong (){

ReturntimeLong;

}

Publicvoid setTimeLong (WeekDay timeLong ){

This. timeLong = timeLong;

}

}

Enum WeekDay {

Mon ("2 h "){

@ Override

PublicString toLocalTime (){

Return "Monday ";

}

},

Tue ("3 h "){

@ Override

PublicString toLocalTime (){

// TODO Auto-generated method stub

Return "Tuesday ";

}

},

Wed ("4 h "){

@ Override

PublicString toLocalTime (){

// TODO Auto-generated method stub

Return "Wednesday ";

}

},

Thu ("5 h "){

@ Override

PublicString toLocalTime (){

// TODO Auto-generated method stub

Return "Thursday ";

}

},

Fri ("6 h "){

@ Override

PublicString toLocalTime (){

// TODO Auto-generated method stub

Return "Friday ";

}

},

Sat ("7 h "){

@ Override

PublicString toLocalTime (){

// TODO Auto-generated method stub

Return "Saturday ";

}

},

Sun ("8 h "){

@ Override

PublicString toLocalTime (){

// TODO Auto-generated method stub

Return "Sunday ";

}

};

 

Private String timeLong;

 

Private WeekDay (StringtimeLong ){

This. timeLong = timeLong;

}

 

 

 

Public StringgetTimeLong (){

ReturntimeLong;

}

 

 

 

Publicabstract String toLocalTime ();

}

Publicclass TestTimeBean {

Publicstaticvoid main (String [] args ){

TimeBean tb = newTimeBean ();

Tb. setName ("James ");

Tb. setTimeLong (WeekDay. Mon );

// Tb. getTimeLong (WeekDay. Mon. toLocalTime ());

String timeLong = WeekDay. Mon. getTimeLong ();

String localTime = WeekDay. Mon. toLocalTime ();

System. out. println (tb. getName () + "..." + localTime + "..." + timeLong );

}

}

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.