The use of generics in Java

Source: Internet
Author: User
Tags class definition

1.Java generics and C + + template
Since Java's generics design is behind the C + + template, Java's generics design absorbs many of the experience and lessons of template. First, unlike the template, generics's declaration requires type checking, and the template does not provide this functionality, which makes the use of generics more secure. In addition, the Java generics program only needs to compile once, all programs can be reused this class bytecode, and the template implementation is for each use template variable compiled into a new class, which will cause some redundant code.

Definition of 2.Generics:
2.1 Class and interface definitions
Here is the simplest generics class definition, which defines a parameterized type T1:

Interface mylist<t1> {...}

The following are interfaces that support multiple parameterized types:

Interface mylist<t1,t2,t3> {...}

Java supports parameterized types with restrictions. In the following example, the T1 type must implement the class comparable interface, and the T2 type must be a subclass of the component class.

Interface Implements extends component> {}


A complex definition can have a qualified declaration and can even use a forward reference.

class Implements Implements convertibleto<a>{}

The definition of class is basically the same as interface, which is no longer detailed here.

2.2 Definition of the method
In a method, by defining a parameterized type, you can increase the abstraction level of the method and improve its reusability. The list of parameterized types for a method is placed after the method modifier, before the value is returned. Such as:

 Public Static  void swap (elem[] A,int i,int  j)   Elem temp=a[i];   A[i]=a[j]   a[j]=temp;}

2.3 Practical Examples
One but the Java language supports most of the classes in Generics,collection will be rewritten in generics manner. Example: Definition of Hashtable with generics overrides

 Public class extends Implements Map<k,v>, java.lang.Cloneable, java.io.Serializable {  public  V put (K key, V value) {...} ... ..}

Unlike the previous Hashtable definition, it adds two to the expression key and value parameterized types (K,V), since both dictionary and map support generics, so they all use the generics expression.

Use of 3.Generics:
3.1 Creating Objects
Before using the generics class, you must initialize by definition, set the actual type of the parameterized type, and the following are some examples of constructing hashtable and vectors.

hashtable<integer,string> ht1=New hashtable<integer,string>(); Hashtable<Integer,String> ht2=null; Vector<String> v1=new vector<string>(); Vector<Integer> v2=new Vector<integ

3.2 Classes for generics objects
In the above example, for V1 and V2 objects, they are all objects of the vector class, they have the same class type, in other words, at run time, the following expression is true. Although they are created with different parameter types, their class types are the same. Assert (V1.getclass (). Equals (V2.getclass ()));

However, if we define a method with a vector parameter, when the method is called, a vector object is passed in, which causes the compilation to fail. This is because at compile time, these two objects are treated as different types.

void  Method (Vector<string> v) {};.. Vector<Integer> v2=new vector<integer>(); Method (v2); // Compilation failed

cast of Class 3.3
For the principle of forced conversion of the generics class, we can use common conversion rules to operate. It is important to note that there is no conversion between objects of different parameterized types as defined by the same generics class. For example, there is no conversion between vector and vector. Also, object cannot be converted to generics type, but the generics class can be converted to object.

Here are some examples of conversions

Class dictionary<a,b>extendsObject{}class Hashtable<A,B>extendsDictionary<a,b>{}dictionary<String,Integer> d=NewDictionary<string,integer>(); Hashtable<String,Integer> h=NewHashtable <String,Integer>(); Hashtable<Float,Double> hfd=NewHashtable<float,double>(); Object o=NewObject ();1) d= (dictionary<string,integer>) H//the compilation succeeds and runs successfully; they have a parent-child class relationship. 2) h= (hashtable<string,integer>) D;//The compilation succeeds, the run fails, and they have a parent-child class relationship. 3) h= (hashtable<string,integer>) o;//compile failed, object cannot be converted into generics class;4) hfd= (hashtable<float,double>) D;//compilation failed;

The use of generics in Java

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.