Basic introduction and use of Java generic generics

Source: Internet
Author: User
Tags comparable

Now began to learn more about Java generics, has been only in the collection of simple use of generics, simply do not understand the principle and role of generics. Generics are a very important feature in Java, so be very well researched.

I. Basic concepts of generics

Generic definition: Generics are a new feature of JDK 1.5, which is essentially an application of the parameterized type (parameterized type), which means that the data type being manipulated is specified as a parameter, specifying a specific type when used. This type of parameter can be used in the creation of classes, interfaces, and methods, which are referred to as generic classes, generic interfaces, and generic methods, respectively.

Generics are beginning to sprout in the C + + language template (Templates), and when the Java language is in a version that does not yet appear generic, the type generalization can only be achieved through object being a combination of all types of parent classes and types that cast two features. For example, in the access to the hash table, JDK 1.5 uses the HashMap get () method, the return value is an object, because all the types in the Java language inherit from Java.lang.Object, it is possible to transform object to any object Chengdu. But because of the infinite possibilities, only the programmer and the runtime virtual machine know what type of object this object is. During compilation, the compiler was unable to check whether the coercion of this object was successful, and if only the programmer was able to ensure the correctness of the operation, many classcastexception risks would be passed on to the program run time.

The use of generics in C # and Java seems to be the same, but there are fundamental differences in implementation, C # inside the generic type in the program source code, compiled Il (Intermediate Language, intermediate language, This time the generic is a placeholder) or the runtime of the CLR is a real existence of,list<int> and list<string> is two different types, they are generated during the system runtime, have their own virtual method table and type data, this implementation is called type expansion, Generics that are implemented based on this method are called real generics.

Generics in the Java language are different, it exists only in the program source code, in the compiled bytecode file, has been replaced with the original original type (raw type, also known as the bare type), and in the appropriate place to insert the forced transformation code, so for the runtime of the Java language, Arraylist<int> and arraylist<string> are the same class. So generics are actually a syntactic sugar in the Java language, and generic implementations in the Java language are called type Erasure, and generics implemented based on this approach are called pseudo generics. (Type erase in the back in learning)

program code written using the generic mechanism has better security and readability than the clutter of code that uses the object variable and then enforces the type conversion. Generics are especially useful for collection classes.

Generic Programming (Generic programming) means that the code you write can be reused by many different types of objects.

Example Analysis:

Prior to JDK1.5, Java generic programming was implemented with inheritance. Because the object class is the base class for the class you are using, you only need to maintain a reference to the object type. For example, ArrayList only maintains an array of object references:

[Java]View PlainCopy
    1. Public class ArrayList//jdk1.5 before the
    2. {
    3. Public Object Get (int i) {...}
    4. public Void Add (Object o) {...}
    5. ......
    6. private object[] elementdata;
    7. }

This will have two problems:

1, no error checking, you can add the class object to the array list

2, when the element is taken, the forced type conversion is required

In this way, errors can occur easily, such as:

[Java]View PlainCopy
    1. /**jdk1.5 before the writing, prone to problems * *
    2. ArrayList arraylist1=New ArrayList ();
    3. Arraylist1.add (1);
    4. Arraylist1.add (1L);
    5. Arraylist1.add ("ASA");
    6. int i= (Integer) arraylist1.get (1); Because you do not know the type of the value being taken out, the type conversion is error prone

The first element here is a long integer, and you think it's plastic, so there's an error in the strong turn.

So. After JDK1.5, generics are added to solve similar problems. For example, using generics in ArrayList:

[Java]View PlainCopy
  1. /** jdk1.5 after adding generics * /
  2. arraylist<string> arraylist2=New arraylist<string> (); //Qualify the type in the array list
  3. Arraylist2.add (1); Cannot add reshape because the type is qualified
  4. Arraylist2.add (1L);//Because the type is qualified, you cannot add an integral long shape
  5. Arraylist2.add ("ASA"); Only strings can be added
  6. String Str=arraylist2.get (0); Forced type conversions are not required because you know the type of the value being taken out

Also understand that the generic feature is forward-compatible. Although many of the classes in the standard class library of JDK 5.0, such as the collection framework, are already generic, existing code that uses collection classes (such as HASHMAP and ArrayList) can continue to work in JDK 1.5 without modification. Of course, existing code that does not take advantage of generics will not win the benefits of type-safety for generics.

Before learning generics, briefly introduce some basic terms of generics, with Arraylist<e> and arraylist<integer> as a brief introduction:

The whole becomes arraylist<e> generic type

E in arraylist<e> is called a type variable or type parameter

The entire arraylist<integer> is called a parameterized type

An Integer in arraylist<integer> is called an instance of a type parameter or an actual type parameter

· The <Integer> in arraylist<integer> is typeof Integer

ArrayList called primitive types

Second, the use of generics

The parameter types of generics can be used in the creation of classes, interfaces, and methods, respectively, as generic classes, generic interfaces, and generic methods. Here's a look at how it's defined.

1. Definition and use of generic classes

A generic class (generic Class) is a class that has one or more type variables. It is very simple to define a generic class, just add <> to the class name, and then add the type parameter to it:

[Java]View PlainCopy
  1. Class Pair<t> {
  2. private T value;
  3. Public Pair (T value) {
  4. This.value=value;
  5. }
  6. Public T GetValue () {
  7. return value;
  8. }
  9. public void SetValue (T value) {
  10. this.value = value;
  11. }
  12. }
Now we can use this generic class:
[Java]View PlainCopy
  1. Public static void Main (string[] args) throws classnotfoundexception {
  2. pair<string> pair=New pair<string> ("Hello");
  3. String Str=pair.getvalue ();
  4. System.out.println (str);
  5. Pair.setvalue ("World");
  6. Str=pair.getvalue ();
  7. System.out.println (str);
  8. }

The pair class introduces a type variable t, enclosed in angle brackets <>, and placed behind the class name. A generic class can have more than one type variable. For example, you can define a pair class, where the first and second fields use different types:

public class pair<t,u>{...}

Note: Type variables are used in uppercase and relatively short, which is very common. In the Java library, the variable e is used to represent the element type of the collection, and K and V represent the type of the keyword and value, respectively. (You can also use the adjacent letters U and s) to indicate "any type" when needed.

2, the definition and use of generic interface

To define generic interfaces and generic classes, see the following simple example:

[Java]View PlainCopy
  1. Interface show<t,u>{
  2. void Show (T t,u U);
  3. }
  4. Class Showtest implements show<string,date>{
  5. @Override
  6. public Void Show (String str,date Date) {
  7. System.out.println (str);
  8. SYSTEM.OUT.PRINTLN (date);
  9. }
  10. }

Test it:

[Java]View PlainCopy
    1. Public static void Main (string[] args) throws classnotfoundexception {
    2. Showtest showtest=New Showtest ();
    3. Showtest.show ("Hello",new Date ());
    4. }


3. Definition and use of generic methods

A generic class enforces type constraints among multiple method signatures. In list<v>, the type parameter V appears in the signatures of methods such as Get (), add (), contains (), and so on. When creating a variable of type map<k, v>, you declare a type constraint between the methods. The value you pass to add () will be the same as the type of the value returned by Get ().

Similarly, it is common to declare a generic method because you want to declare a type constraint between multiple parameters of the method.

To give a simple example:

[Java]View PlainCopy
  1. Public static void Main (string[] args) throws classnotfoundexception {
  2. String str=get ("Hello", "World");
  3. System.out.println (str);
  4. }
  5. public static <t, u> t get (T T, u u) {
  6. if (U = null)
  7. return t;
  8. Else
  9. return null;
  10. }



Iii. type-qualification of generic variables

On top of that, we simply learned about generic classes, generic interfaces, and generic methods. We all use the form of <T> to complete the declaration of a generic type directly.

Sometimes a class, interface, or method needs to constrain a type variable. Look at the following example:

There is such a simple generic method:

[Java]View PlainCopy
    1. Public static <T> t get (t t1,t T2) {
    2. if (T1.compareto (T2) >=0); Compile error
    3. return t1;
    4. }

Because, before compiling, that is, we are still defining this generic method, we do not know what type of generic type T is, and so, only the default T is the original type object. So it can only invoke the few methods from object, not the CompareTo method.

But my intention is to compare T1 and T2, how to do? At this point, you do this by using a type-qualified, set qualification (bound) on the type variable T.

We know that all methods that implement comparable interfaces will have CompareTo methods. So, you can define <T> as follows:

[Java]View PlainCopy
    1. Public static <t extends comparable> t get (t t1,t T2) { //Add type qualification
    2. if (T1.compareto (T2) >=0);
    3. return t1;
    4. }


Type qualification can be used in generic classes, generic interfaces, and generic methods, but be aware of the following points:

1, whether the qualification is a class or interface, unified use the keyword extends

2, you can use the & symbol to give a number of qualifications, such as

[Java]View PlainCopy
    1. Public static <t extends comparable&serializable> t get (t t1,t T2)

3, if there is a limit to the existing interface and class, then the class must be only one, and placed in the first place

[Java]View PlainCopy
        1. Public static <t extends object&comparable&serializable> t get (t t1,t T2)

Basic introduction and use of Java generic generics

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.