Generics _effective Java 2.0_item 1 knowledge points in Java __java

Source: Internet
Author: User
Tags comparable inheritance uppercase letter java keywords
article author: Tyan

Blog: noahsnail.com 1. What is generics

Java generics (generics) is a new feature introduced in JDK 5, which allows you to use type parameters when defining classes and interfaces (type parameter), which are also called parameterized types (parameterized Type) or parametric polymorphism (parametric polymorphism). The main application of generics is in the new collection class framework in JDK 5. The application of Java generics can improve the reusability of code, while generics provide type checking, reduce the type conversion of data, and ensure the type safety of compile-time. the advantages of 1.1 Java generics

Java generics maintain good compatibility with the Java language and Java virtual machines, and here's a brief overview of the features of Java generics:

Type safety. One of the main goals of generics is to improve the type safety of Java programs. Using generics enables the compiler to know the type limits of a variable, and thus to a higher degree to validate the type hypothesis. Without generics, the security of types is largely handled by the programmer, which is obviously less secure than a generic program.

Eliminates coercion type conversions. Generics can eliminate many of the coercion type conversions in the source code, which makes the code more readable and reduces the chance of error.

Backward compatibility. Java compilers that support generics, such as the Javac in JDK5.0, can be used to compile generic extensions of Java programs (Java generics programs), but existing Java programs that do not use generic extensions can still be compiled with these compilers.

Clear level, adhere to the norms. Regardless of whether the compiled source program uses generic extensions, the compiled bytecode can be accepted and executed by the virtual machine. That is, regardless of whether the compiler's input is a Java generic program, or a generic Java program, the compiled bytecode strictly follows the requirements for bytecode in the Java Virtual Machine specification. Visible, generics are implemented primarily at the compiler level and are transparent to Java virtual machines.

Performance gains. For the time being, code written in Java generics is very efficient in terms of efficiency and general Java code. However, because generics bring more type information to the Java compiler and virtual machines, it is possible to use this information to further optimize the Java program. 1.2 matters to be aware of using Java generics

Some basic principles can be followed when using generics to avoid some common problems.

Avoid mixing of generic and original types in your code. For example, list and list should not be used together. This results in some compiler warnings and potential run-time exceptions. When you have to take advantage of the legacy code that was developed prior to JDK 5 and have to do so, isolate the relevant code as much as possible.

When using generic classes with wildcard characters, you need to define the concept of a set of types that the wildcard represents. Because the specific type is unknown, many operations are not allowed.

Generic classes are best not used with arrays. You can only create new List 2. Some concepts related to generics 2.1 type Erase

The first prerequisite for a proper understanding of generic concepts is to understand type erasure. Generics in Java are basically implemented at the level of the compiler. Type information in the generated Java byte code that does not contain a generic type. The type parameters that are added when using generics are removed by the compiler at compile time. This process is called type erasure. Types such as lists and lists, defined in code, become list after compilation. The JVM sees only the list, and the type information attached by generics is not visible to the JVM. The Java compiler can find where possible errors at compile time, but still cannot avoid the occurrence of a type conversion exception at run time. Type erasure is also an important difference between Java's generics implementation and the C + + template mechanism implementation approach.

Many of the strange properties of generics are related to the existence of this type of erasure, including:

Generic classes do not have their own unique class object. For example, there is no list.class or list.class, and only List.class.

Static variables are shared by all instances of the generic class. For classes declared as MyClass, the method of accessing the static variables in them is still myclass.mystaticvar. Objects created either through new MyClass or new MyClass share a static variable.

A generic type parameter cannot be used in a catch statement in Java exception handling. Because exception handling is performed by the JVM at run time. Because type information is erased, the JVM cannot distinguish between two exception types MyException and MyException. For the JVM, they are all myexception types. You cannot perform a catch statement that corresponds to an exception.

The basic process of type erasure is also simpler, first of all, to find the specific class used to replace the type parameter. This particular class is generally object. This upper bound is used if the upper bound of the type parameter is specified. Replace the type parameters in the code with the specific classes. At the same time remove the occurrence of the type declaration, that is, remove <> content. For example, a T get () method declaration becomes an object get (), and the list becomes a list. Next you may need to generate some bridging methods (bridge method). This is because the class after erasing the type may be missing some of the necessary methods. For example, consider the following code:

Class MyString implements comparable<string> {public
    int compareTo (String str) {return        
        0;    
    }

When the type information is erased, the declaration of the class above becomes the class MyString implements comparable. But in this case, the class mystring will have compile errors because there is no int compareTo (Object) method that implements the interface comparable declaration. This is the time for the compiler to dynamically generate this method.

Once you understand the type erasure mechanism, you will understand that the compiler assumes full type checking. The compiler prohibits certain generics from being used precisely to ensure the security of the type. Take the list and list mentioned above as examples to specifically analyze:

public void Inspect (list<object> List) {for    
    (Object obj:list) {        
        System.out.println (obj);    
    }    
    List.add (1); This operation is valid in the context of the current method. 
}
public void Test () {    
    list<string> STRs = new arraylist<string> ();    
    Inspect (STRs); Compile Error 
}  

In this code, the inspect method accepts the list as an argument, and a compilation error occurs when you try to pass in the list in the test method. Assuming such an approach is permissible, then the inspect method can add a number to the collection by List.add (1). Thus, in the view of the test method, an integer-type object is added to the collection whose declaration is a list. This is clearly a violation of the principle of type safety, and at some point it will definitely throw classcastexception. Therefore, the compiler prohibits such behavior. The compiler checks for possible type-safety issues as much as possible. A compilation error is given to determine where the relevant principles are violated. A warning message is given when the compiler is unable to determine whether the type is being used correctly. 2.2 wildcard characters and upper and lower bounds

When using a generic class, you can specify a specific type, such as a list declaring that the specific type is string, or you can use wildcard characters to represent unknown types, such as List

public void wildcard (list<?> List) {
    list.add (1);//Compile Error 

As shown above, there is always a compile error when attempting to manipulate a generic class with wildcard characters. The reason for this is that the type represented by the wildcard character is unknown.

Because for the list 2.3 type system

In Java, you are more familiar with the type architecture that is generated by inheritance mechanisms. For example, string inherits from object. According to the Liskov substitution principle, subclasses can replace the parent class. When you need a reference to the object class, there is no problem if you pass in a string object. But conversely, when you replace a subclass reference with a reference to a parent class, you need to cast the coercion type. The compiler does not guarantee that this conversion must be legal at run time. This automatic subclass replaces the type conversion mechanism of the parent class, which is also true for arrays. String[] can replace object[]. But the introduction of generics has a certain effect on this type of system. As the list mentioned earlier, you can't replace the list.

The type system after the introduction of generics adds two dimensions: one is the inheritance architecture of the type parameter itself, and the other is the inheritance architecture of the generic class or interface itself. The first refers to situations where the type parameter string is inherited from object for cases such as list and list. The second refers to the list interface inheriting from the collection interface. For this type of system, there are some rules:

The relationship of a generic class of the same type parameter depends on the inheritance architecture of the generic class itself. The list is a subtype of collection, and list can replace collection. This is also true for type declarations with upper and lower bounds.

When wildcard characters are used in the type declaration of a generic class, their subtypes can be expanded on two dimensions. such as the collection 2.4 Bridge method

Http://www.cnblogs.com/ggjucheng/p/3352519.html 3. Generic class

An example of a typical generic class is the ArrayList class:

public class Arraylist<e> extends abstractlist<e>
        implements List<e>, Randomaccess, Cloneable, java.io.Serializable {

}

Use it without saying much. 4. Generic interface

A typical generic interface example is the comparable interface:

Public interface Comparable<t> {

    ...

    public int compareTo (T o);

    ...
}

Usage:

public class Test implements comparable<string>{

    @Override public
    int compareTo (String o) {return
        0;
    }
}
5. Generic method
public class Util {public
    static <k, v> Boolean compare (Pair<k, v> p1, pair<k, v> p2) {
        retur n P1.getkey (). Equals (P2.getkey ()) &&
               p1.getvalue (). Equals (P2.getvalue ());
    }
6. Generic Naming conventions

To better understand generics, we also need to understand the naming conventions for Java generics. To differentiate from Java keywords, java generic parameters are defined using only one uppercase letter. The meanings of the various common generic parameters are as follows:

E-element, commonly used in Java collection, such as: List,iterator,set

K,v-key,value, a key value pair representing the map

N-number, Digital

T-type, types, such as String,integer, etc.

Resources:

1, Http://www.infoq.com/cn/articles/cf-java-generics

2, https://www.ibm.com/developerworks/cn/java/j-lo-gj/

3, http://peiquan.blog.51cto.com/7518552/1302898

4, https://docs.oracle.com/javase/tutorial/java/generics/

5, effective Java 2.0

Related Article

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.