The role of Java generics and its basic concepts

Source: Internet
Author: User
Tags comparable

I. Basic concepts of generics

Java, like C #, has the concept of generics and the parameterization of types. Generics in Java appear after jdk5.0, but generics in Java are fundamentally different from generics in C #, starting with the collection type, arraylist<integer> and arraylist<string in Java. > is the same type, it performs type erasure at compile time, and the type in Java is pseudo generic, pseudo generics will be described later, and secondly, when adding basic types of data to a collection such as int, the int will first be converted to an integer object, which is what we typically call a boxing operation. The Interger object needs to be converted to an int value type when the element is taken out, that is, the unboxing operation. Whereas in C #,,list<int> and list<string> are different types, generic parameters are a placeholder after compilation, are not erased, are given a true type at run time, they are generated during system run time, have their own virtual method table and type data, This implementation is called type bloat (for type bloat, the instant compiler has done a lot of optimization to solve this problem), which is called true generics. At the same time, when you add basic elements such as int to a collection, you do not need a boxing operation, and you do not need to unpack the elements when you remove them, so performance is better than Java's set generics.

The introduction of generics in Java is mainly to solve two aspects of the problem: 1. The collection type element has a type reload exception at run time, increases the compile-time type check, and 2. When the code is written, it can reuse the algorithm. The following examples illustrate compiler type checking.

First, let's look at an example that doesn't use generics:

ArrayList al = new ArrayList (); Al.add ("abc"); Al.add ("124"); Al.add ("32L");

We can add any type of data to the Al collection. When we take out the data, we need to type the conversion, such as:

string s = (string) al.Get(0= (string) al.Get(1//At run time, error, type conversion errors = (Long) al.Get(2);

As a result, when there is no generics, the compile-time type checking is reduced, and the programmer needs to know the type of each element when extracting the element, otherwise the type conversion exception is likely to occur at run time.

So let's look at the generic collection to see the benefits he brings to us.

New Arraylist<string> (); Al1.add ("ABC"); Al1.add (1)   ; //compile times wrong,

When we instantiate the AL1 with the string parameter type, we cannot add the int element, otherwise the compiler will error, usually in the IDE editor, such as Eclipse, there will be a false identity, at the same time, the element is not required to remove the type conversion.

string value = Al1. Get (0); No type conversions required

This is the benefit of generics.

Then the reuse of the algorithm is mainly in the body now, the method of reuse, such as ArrayList's Add method can be used on any type or qualified type.

Second, the use of generics

Generics in Java are primarily used in classes, methods, and interfaces. First, let's take a simple look at the use of the class:

Class Factory<t>{private T value;public T GetValue () {return value;} public void SetValue (T v) {this.value = V;}}

To add a test method:

    factory<string> f = new factory<string> ();    F.setvalue ("factory in Use");    System.out.println (F.getvalue ());

Use of generic interfaces:

Interface myinterface<t,u>{void Show (T T, u u);} Class Showtest implements myinterface<string,integer>{@Overridepublic void Show (String T, Integer u) { System.out.println (t); SYSTEM.OUT.PRINTLN (U);}}

When a generic type parameter acts on a class, it is primarily a type constraint between multiple fields and method signatures. When acting on the method is mainly to the method of the parameters of the corresponding constraints, where the generic type parameters of the method is no longer an example, the following we mainly introduce the constraints of the type parameters.

Three, type parameter constraints

Let's look at a small example, as shown in the following code:

public static <T> t get (t t1,t T2) {      if (T1.compareto (T2) >=0);//Compilation error  , the method CompareTo (t) is undefine D for the type T.    return t1;  }  

can see the compiler error information, for type T does not define the CompareTo method, in Java type needs to be compared to implement the comparable interface, thus overriding the method. Then we make the following changes:

public static <t extends comparable> t get (t t1,t T2) {//Add type          -qualified if (T1.compareto (T2) >=0);          return t1;      

By qualifying T extends comparable it is shown that T is the type of interface that implements the comparable, so the CompareTo method is implemented so that no compile-time errors are generated.

We can use & to divide multiple qualifications for a type, and only use extends for qualified keywords. At the same time, in the case where both the interface and the type exist, the class can only be placed on the first and only one, as follows:

<t extends Object&comparable&serializable>

Reference Source: http://blog.csdn.net/lonelyroamer/article/details/7864531

  

 

  

The role of Java generics and its basic concepts

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.