New characteristics of 25--JDK 9-Generic 1-Deepen introduction

Source: Internet
Author: User

1. The idea of generics

generics are a security mechanism that occurs after JDK1.5. < > To specify the type of elements in a container

JDK5 previously, objects that were saved to the collection would lose their attributes, and often the programmer would have to manually cast the type when taken out, which would inevitably raise some security issues with the program. For example:

ArrayList list = Newarraylist ();

List.add ("abc");

Integer num = (integer) list.get (0); Error at run time (string cannot be strong to integer) but not found in encoding

List.add (New Random ());

List.add (New ArrayList ());

For (Inti=0;i<list.size (); i++) {

(?)          List.get (i); What type of object should be converted here, when written, the programmer cannot confirm

}

2. Generics Benefits:

1. Transfer problems that occur during the runtime to the compile time.

2. Avoid the hassle of forcing type conversions

Generics in JDK5 allow programmers to limit the processing type of a collection when they write collection code, thereby improving the readability and stability of the program (especially in large programs) by turning the original program runtime into a problem that might occur at compile time.

Note: generics are provided to the Javac compiler, which is used to qualify the input type of the collection, allowing the compiler to block the insertion of illegal data into the collection at the source level. However, after the compiler compiles a Java program with a generic shape, the generated class file will no longer have the generic information in it, making the program operational efficiency unaffected, a process called "erase".

L The basic terminology of the generic, take arraylist<e> as an example:<> read typeof

E in arraylist<e> is called type parameter variable

The Integer in arraylist<integer> is called the actual type parameter

the entire called arraylist<e> generic type

• The entire arraylist<integer> is called a parameterized type Parameterizedtype

3. Generic model Applications

Example One: Use an iterator to iterate through the elements in a generic collection.

   

Example two: using an enhanced for loop to iterate over elements in a generic collection

Example Three: accessing the elements in HashMap

packageCom.java.Demo;

importJava.util.HashMap;

importJava.util.Map;

importJava.util.Set;

importorg.junit.Test;

Publicclass Demo2 {

@Test

publicvoid test1 () {

map<integer,string> m = new Hashmap<integer, string> ();

M.put (1, "a");

M.put (2, "B");

M.put (3, "C");

M.put (4, "D");

Set<map.entry<integer,string>>set = M.entryset ();

for (map.entry<integer,string> Me:set) {

System.out.println (Me.getkey () + "..." +me.getvalue ());

}

}

}

4. Several common problems when using generics:

When using a generic, the generic type must be a reference type and cannot be a base data type

use the types on both sides of the generic type must be consistent

arraylist<string> list= New arraylist<object> (); Wrong

arraylist<object> list= New arraylist<string> (); Wrong

arraylist<string> list= New arraylist<string> (); Yes

only one side of both sides can also be used (to maintain compatibility), Generics in the Java language are maintained backwards-compatible, that is, we can go on with the past practice without generics

arraylist<string> list= New ArrayList (); Yes

ArrayList list = newarraylist<string> (); Yes

Compile hints are output when you compile a collection class that does not have a generic mechanism in a high version development environment

static methods can not use generics defined in a class. because generics in a class need to specify a specific type when the object is initialized. and static precedence exists with objects. A generic is defined on a static method, and must be written after the static keyword. Returns the front of a value type

A generic method enables the method to change independently of the class. Here is a basic guideline:

Whenever you can, you should use a generic method as much as possible, that is, if you use a generic method to replace this class of generics, you should use only the generic method , because it can be clearer .

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.