Java Basic Knowledge---jdk5 new features

Source: Internet
Author: User
Tags iterable wrapper

Jdk5.0 new features:

Collection after jdk1.5, there is a parent interface iterable, the appearance of this interface will be extracted iterator method, improve the extensibility.

--------------------------------------------------

Enhanced for Loop: foreach statement,foreach simplifies iterators.

Format://enhanced for loop parentheses write two arguments, the first is to declare a variable, and the second is a container that needs to be iterated

For (element type variable name: Collection collection & array) {

. ..

}

the difference between an advanced for loop and a traditional for loop:

The advanced for loop, when used, must specify the target to be traversed. This target can be a collection collection or array, and if you traverse the collection collection, you need to manipulate the elements in the traversal, such as deletion, and you need to use iterators.

If you are traversing an array, you also need to manipulate the arrays of elements, and it is recommended that you use a traditional for loop because you can define a corner to manipulate elements by using a corner label. If you are only fetching for traversal, you can simplify the advanced for loop, which appears to simplify writing.

The advanced for Loop can traverse the map collection. not at all. However, you can convert the map to set and then use the foreach statement.

 

1. Function: iterate over the container of the storage object: Array Collection map

2), enhancing the For-loop iterative algebra Group:

String[] arr = {"A", "B", "C"};//the static definition of an array, only when the array is first defined

for (Strings:arr) {

System.out.println (s);

}

3), single column collection Collection:

Listlist = new ArrayList ();

List.add ("AAA");

Enhances the For loop, not using a generic collection can use an enhanced for loop iteration. Yes

For (Object obj:list) {

string s = (string) obj;

System.out.println (s);

}

4), two-column collection Map:

Map map= new HashMap ();

Map.put ("A", "AAA");

//Traditional way: Must master this way

Setentrys = Map.entryset (); 1. Get all the key values on the entry object

ITER =entrys.iterator (); 2. Iterate over all the entry

while (Iter.hasnext ()) {

Map.entry Entry = (Entry) iter.next ();

String key = (string) entry.getkey (); Get key and value separately

String value = (string) entry.getvalue ();

SYSTEM.OUT.PRINTLN (key + "=" +value);

}

//Enhanced for loop iteration: in principle, the map collection cannot be iterated with an enhanced for loop because an enhanced for loop can only iterate over a collection that implements the Iterable interface; iterable is the newly defined interface in Jdk5. In the case of a method iterator method, only the class that implements the Iterable interface can guarantee that there must be a iterator method, and Java has this qualification because the enhanced for loop is implemented internally or by an iterator, and in fact, we can use the enhanced for loop in some way.

For (Object Obj:map.entrySet ()) {

map.entryentry = (Entry) obj; Obj in turn represents entry

System.out.println (Entry.getkey () + "=" + Entry.getvalue ());

}

5), set iterative attention problem: in the process of iterative collection, the collection can not be added or deleted operations (will report concurrent access to the exception); The iterator method may be used to operate (subclass Listiterator: There are additions and deletions to the method).

6), enhance the For loop attention problem: When using the enhanced for loop, the element cannot be assigned;

Int[]arr = {1,2,3};

for (Intnum:arr) {

num = 0; Cannot change the value of an array

}

System.out.println (arr[1]);//2

--------------------------------------------------

variable parameters (...). ): Use the parameters of the function, when the number of the same type of element to operate is uncertain, but in this way, this parameter can accept any number of the same type of data.

Unlike previously received arrays, the following are:

Before defining an array type, you need to create an array object and then pass the array object as a parameter to the function. Now, simply pass the elements in the array as arguments. The bottom layer is actually the encapsulation of the array of these elements, and this encapsulation action is done at the bottom, and is hidden. So the user's handwriting is simplified, and the action of the caller-defined array is less.

If you use a variable parameter in the parameter list, the variable parameter must be defined at the end of the argument list (that is, the last argument must be the one), or the compilation will fail. )。

If you want to get the number of ints. You can use to encapsulate multiple int into an array, and then sum the arrays directly.

---------------------------------------------------

static import: all static members in a class are imported, simplifying the writing of static members.

Import static java.util.collections.*; All static members in the collections class were imported

---------------------------------------------------

enumerations: keyword enum

problem: The value of an object's property cannot be arbitrary and must be a fixed set of one of the values;

Solution:

1), in the Setgrade method to make judgments, do not meet the format required to throw an exception;

2, directly restrict the user's choice, through the custom class simulates the enumeration the way to limit the user's input, writes a grade class, the private constructor function, provides 5 static constants to represent the class instance;

3), Jdk5, the new enumeration types are defined, specifically for solving such problems;

4), enumeration is a special Java class, you can define attributes, methods, constructors, implementation interfaces, inheritance classes;

------------------------------------------------------------------------------

Auto-unboxing:There are two kinds of data types in Java: Basic data type Reference data type (object)

All data in a Java program needs to be treated as objects, and a wrapper class is provided for 8 basic data types, as follows:

int--> Integer

BYTE--> byte

Short--> Short

Long--> Long

Char--> Character

Double--> Double

Float--> Float

Boolean--> Boolean

Jdk5 the previous basic data types and wrapper classes need to be transferred to each other:

The base---references integer x = new integer (x);

Reference---base int num = X.intvalue ();

1), Integer x = 1;  x = x + 1; What the process is going through. packing à unpacking à box ;

2), in order to optimize, the virtual machine provides the buffer pool for the wrapper class, thesize of the integer pool -128~127 a byte size ;

3),string pool:Java provides a buffer pool for optimizing string manipulation;

----------------------------------------------------------

generics:A security mechanism that appears after the jdk1.5 version. Expression format:<>

Benefits:

1: The runtime of the problem classcastexception problem conversion into a compilation failure, reflected in the compile time, the programmer can solve the problem.

2: Avoid the hassle of forced conversions.

As long as a class or interface with <> is a class or interface with a type parameter, it is necessary to pass a specific reference data type to <> when using these classes or interfaces.

Generic technology: In fact, the application in the compile-time, is to the compiler to use the technology, to the runtime, generics will not exist.

Why? Because of a generic erase : That is, the editor checks that the generic type is correct, and that there is no generics in the generated class file.

at run time, how do I know what type of element to get without a strong turn?

compensation for generics : Because the type has been identified as an element of the same type at runtime, the user does not have to do the conversion action at run time, as long as the type of the element is acquired and a single conversion is made internally.

when do you use generic classes?

when the reference data type of an operation in a class is indeterminate, the object used previously is extended and can now be represented as a generic type. This avoids the hassle of a hard turn and shifts the running problem to the compile time.

----------------------------------------------------------

generics are embodied in the definition of a program:

//Generic class: Defines a generic on a class.

Class Tool<q> {

Private Q obj;

public void SetObject (Q obj) {

This.obj = obj;

}

Public Q GetObject () {

return obj;

}

}

//When the reference data type of the method action is indeterminate, the generics can be defined on the method.

Public <W> Voidmethod (w) {

System.out.println ("Method:" +w);

}

//static method generics: Static methods cannot access generics defined on the class. If the reference data type of a static method operation is indeterminate, you must define the generic on the method.

Public static<q> void function (Q t) {

System.out.println ("function:" +t);

}

//generic interface.

Interface Inter<t> {

void Show (t);

}

Class Interimpl<r> implements Inter<r> {

public void Show (R) {

System.out.println ("Show:" +r);

}

}

------------------------------------------------------------

wildcard characters in generics: can be resolved when the specific type of uncertainty, this wildcard is ? When manipulating a type, you use only the features in the object class when you do not need to use the specific functionality of the type. So you can use it? Wildcard table unknown type.

Generic Qualification:

Ceiling:. Extends e: Can receive subtype objects of type E or E.

Lower:. Super E: Can receive a parent type object of type E or E.

When to use the upper bound: when adding elements to the collection, you can add both an type E object and a subtype object of E. Why. Because the type E can receive both the Class E object and the subtype object of E when it is taken.

When the lower limit is used: when an element is fetched from the collection, it can be received with the type of the current element, or it can be received with the current element's parent type.

details of generics:

1), what type of generics represents depends on the type of caller, if not, the default is type object;

2. When creating an object with a generic class, the generic type specified on both sides of the equation must be consistent;

Reason: The compiler checks the object invocation method to see only the variable, but when the program is running the method should consider the object specific type;

3, the equation on either side can be used on either side of the generic, on the other side do not use (consider backward compatibility);

Arraylist<string>al = new arraylist<object> (); Wrong

//To ensure that the right and left sides of the generic specific type is consistent, so it is not easy to make mistakes.

Arraylist<?extends object> al = new Arraylist<string> ();

Al.add ("AA"); Wrong

Because it is possible to store string in a collection-specific object or to store other subclasses of object, it is not appropriate to add specific type objects, and type checking can cause security problems. Extendsobject represents the subtype of an object, how can you add a specific type of object?

public static Voidmethod (arraylist<? extends Object> al) {

Al.add ("abc"); Wrong

//Only methods in the object class can be called on elements in the Al collection, and methods of the specific subtypes are not available because the subtype is indeterminate.

}

--------------------------------------------------------------------------------------------------------------- ---------------------------------

Jdk5.0 new features:

Collection after jdk1.5, there is a parent interface iterable, the appearance of this interface will be extracted iterator method, improve the extensibility.

--------------------------------------------------

Enhanced for Loop: foreach statement,foreach simplifies iterators.

Format://enhanced for loop parentheses write two arguments, the first is to declare a variable, and the second is a container that needs to be iterated

For (element type variable name: Collection collection & array) {

. ..

}

the difference between an advanced for loop and a traditional for loop:

The advanced for loop, when used, must specify the target to be traversed. This target can be a collection collection or array, and if you traverse the collection collection, you need to manipulate the elements in the traversal, such as deletion, and you need to use iterators.

If you are traversing an array, you also need to manipulate the arrays of elements, and it is recommended that you use a traditional for loop because you can define a corner to manipulate elements by using a corner label. If you are only fetching for traversal, you can simplify the advanced for loop, which appears to simplify writing.

The advanced for Loop can traverse the map collection. not at all. However, you can convert the map to set and then use the foreach statement.

 

1. Function: iterate over the container of the storage object: Array Collection map

2), enhancing the For-loop iterative algebra Group:

String[] arr = {"A", "B", "C"};//the static definition of an array, only when the array is first defined

for (Strings:arr) {

System.out.println (s);

}

3), single column collection Collection:

Listlist = new ArrayList ();

List.add ("AAA");

Enhances the For loop, not using a generic collection can use an enhanced for loop iteration. Yes

For (Object obj:list) {

string s = (string) obj;

System.out.println (s);

}

4), two-column collection Map:

Map map= new HashMap ();

Map.put ("A", "AAA");

//Traditional way: Must master this way

Setentrys = Map.entryset (); 1. Get all the key values on the entry object

ITER =entrys.iterator (); 2. Iterate over all the entry

while (Iter.hasnext ()) {

Map.entry Entry = (Entry) iter.next ();

String key = (string) entry.getkey (); Get key and value separately

String value = (string) entry.getvalue ();

SYSTEM.OUT.PRINTLN (key + "=" +value);

}

//Enhanced for loop iteration: in principle, the map collection cannot be iterated with an enhanced for loop because an enhanced for loop can only iterate over a collection that implements the Iterable interface; iterable is the newly defined interface in Jdk5. In the case of a method iterator method, only the class that implements the Iterable interface can guarantee that there must be a iterator method, and Java has this qualification because the enhanced for loop is implemented internally or by an iterator, and in fact, we can use the enhanced for loop in some way.

For (Object Obj:map.entrySet ()) {

map.entryentry = (Entry) obj; Obj in turn represents entry

System.out.println (Entry.getkey () + "=" + Entry.getvalue ());

}

5), set iterative attention problem: in the process of iterative collection, the collection can not be added or deleted operations (will report concurrent access to the exception); The iterator method may be used to operate (subclass Listiterator: There are additions and deletions to the method).

6), enhance the For loop attention problem: When using the enhanced for loop, the element cannot be assigned;

Int[]arr = {1,2,3};

for (Intnum:arr) {

num = 0; Cannot change the value of an array

}

System.out.println (arr[1]);//2

--------------------------------------------------

variable parameters (...). ): Use the parameters of the function, when the number of the same type of element to operate is uncertain, but in this way, this parameter can accept any number of the same type of data.

Unlike previously received arrays, the following are:

Before defining an array type, you need to create an array object and then pass the array object as a parameter to the function. Now, simply pass the elements in the array as arguments. The bottom layer is actually the encapsulation of the array of these elements, and this encapsulation action is done at the bottom, and is hidden. So the user's handwriting is simplified, and the action of the caller-defined array is less.

If you use a variable parameter in the parameter list, the variable parameter must be defined at the end of the argument list (that is, the last argument must be the one), or the compilation will fail. )。

If you want to get the number of ints. You can use to encapsulate multiple int into an array, and then sum the arrays directly.

---------------------------------------------------

static import: all static members in a class are imported, simplifying the writing of static members.

Import static java.util.collections.*; All static members in the collections class were imported

---------------------------------------------------

enumerations: keyword enum

problem: The value of an object's property cannot be arbitrary and must be a fixed set of one of the values;

Solution:

1), in the Setgrade method to make judgments, do not meet the format required to throw an exception;

2, directly restrict the user's choice, through the custom class simulates the enumeration the way to limit the user's input, writes a grade class, the private constructor function, provides 5 static constants to represent the class instance;

3), Jdk5, the new enumeration types are defined, specifically for solving such problems;

4), enumeration is a special Java class, you can define attributes, methods, constructors, implementation interfaces, inheritance classes;

------------------------------------------------------------------------------

Auto-unboxing:There are two kinds of data types in Java: Basic data type Reference data type (object)

All data in a Java program needs to be treated as objects, and a wrapper class is provided for 8 basic data types, as follows:

int--> Integer

BYTE--> byte

Short--> Short

Long--> Long

Char--> Character

Double--> Double

Float--> Float

Boolean--> Boolean

Jdk5 the previous basic data types and wrapper classes need to be transferred to each other:

The base---references integer x = new integer (x);

Reference---base int num = X.intvalue ();

1), Integer x = 1;  x = x + 1; What the process is going through. packing à unpacking à box ;

2), in order to optimize, the virtual machine provides the buffer pool for the wrapper class, thesize of the integer pool -128~127 a byte size ;

3),string pool:Java provides a buffer pool for optimizing string manipulation;

----------------------------------------------------------

generics:A security mechanism that appears after the jdk1.5 version. Expression format:<>

Benefits:

1: The runtime of the problem classcastexception problem conversion into a compilation failure, reflected in the compile time, the programmer can solve the problem.

2: Avoid the hassle of forced conversions.

As long as a class or interface with <> is a class or interface with a type parameter, it is necessary to pass a specific reference data type to <> when using these classes or interfaces.

Generic technology: In fact, the application in the compile-time, is to the compiler to use the technology, to the runtime, generics will not exist.

Why? Because of a generic erase : That is, the editor checks that the generic type is correct, and that there is no generics in the generated class file.

at run time, how do I know what type of element to get without a strong turn?

compensation for generics : Because the type has been identified as an element of the same type at runtime, the user does not have to do the conversion action at run time, as long as the type of the element is acquired and a single conversion is made internally.

when do you use generic classes?

when the reference data type of an operation in a class is indeterminate, the object used previously is extended and can now be represented as a generic type. This avoids the hassle of a hard turn and shifts the running problem to the compile time.

----------------------------------------------------------

generics are embodied in the definition of a program:

//Generic class: Defines a generic on a class.

Class Tool<q> {

Private Q obj;

public void SetObject (Q obj) {

This.obj = obj;

}

Public Q GetObject () {

return obj;

}

}

//When the reference data type of the method action is indeterminate, the generics can be defined on the method.

Public <W> Voidmethod (w) {

System.out.println ("Method:" +w);

}

//static method generics: Static methods cannot access generics defined on the class. If the reference data type of a static method operation is indeterminate, you must define the generic on the method.

Public static<q> void function (Q t) {

System.out.println ("function:" +t);

}

//generic interface.

Interface Inter<t> {

void Show (t);

}

Class Interimpl<r> implements Inter<r> {

public void Show (R) {

System.out.println ("Show:" +r);

}

}

------------------------------------------------------------

wildcard characters in generics: can be resolved when the specific type of uncertainty, this wildcard is ? When manipulating a type, you use only the features in the object class when you do not need to use the specific functionality of the type. So you can use it? Wildcard table unknown type.

Generic Qualification:

Ceiling:. Extends e: Can receive subtype objects of type E or E.

Lower:. Super E: Can receive a parent type object of type E or E.

When to use the upper bound: when adding elements to the collection, you can add both an type E object and a subtype object of E. Why. Because the type E can receive both the Class E object and the subtype object of E when it is taken.

When the lower limit is used: when an element is fetched from the collection, it can be received with the type of the current element, or it can be received with the current element's parent type.

details of generics:

1), what type of generics represents depends on the type of caller, if not, the default is type object;

2. When creating an object with a generic class, the generic type specified on both sides of the equation must be consistent;

Reason: The compiler checks the object invocation method to see only the variable, but when the program is running the method should consider the object specific type;

3, the equation on either side can be used on either side of the generic, on the other side do not use (consider backward compatibility);

Arraylist<string>al = new arraylist<object> (); Wrong

//To ensure that the right and left sides of the generic specific type is consistent, so it is not easy to make mistakes.

Arraylist<?extends object> al = new Arraylist<string> ();

Al.add ("AA"); Wrong

Because it is possible to store string in a collection-specific object or to store other subclasses of object, it is not appropriate to add specific type objects, and type checking can cause security problems. Extendsobject represents the subtype of an object, how can you add a specific type of object?

public static Voidmethod (arraylist<? extends Object> al) {

Al.add ("abc"); Wrong

//Only methods in the object class can be called on elements in the Al collection, and methods of the specific subtypes are not available because the subtype is indeterminate.

}

--------------------------------------------------------------------------------------------------------------- ---------------------------------

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.