On the function of Java generics and its basic concept _java

Source: Internet
Author: User
Tags comparable

The basic concept of generic type

Java, like C #, has a generic concept and a parameterized type. Generics in Java appear after jdk5.0, but generics in Java are intrinsically different from generics in C #, first from the collection type, arraylist<integer> and arraylist<string in Java > is the same type that performs type erasure at compile time. and the type in Java is pseudo generic, the pseudo generics will be described later, and secondly, for adding basic types of data like a collection, such as int, the int is first converted to an integer object, which is what we usually call boxing operations, You need to convert the Interger object to an int value type, or a unboxing operation, when you remove the element. In C #,,list<int> and list<string> are different types, and generic parameters are compiled with a placeholder that is not erased and is given the true type at run time, they are generated during system runtime, have their own virtual method table and type data, This implementation is called type bloat (for type bloat, the Just-in-time compiler has done a lot of optimizations to solve the problem), and this 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 remove the elements without unpacking, so the performance is better than the Java collection generics.

The introduction of generics in Java is mainly to solve two aspects of the problem: 1. The collection type element has a type-change exception at run time, increases the compile-time type check, and 2. When the code is duplicated, the algorithm can be reused. The following example illustrates the compiler's 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 the type conversion, such as:

string s = (string) al.get (0);
string S1 = (string) al.get (1); At run time, an error is occurred, type conversion errors
long L = (long) al.get (2);

As you can see, when there is no generics, the compile-time type check is reduced, and the programmer needs to know the type of each element when it is taken out, or it is likely that a type conversion exception will occur at run time.

So let's look at the benefits he brings to us by using a generic collection.

arraylist<string> al1 = new arraylist<string> ();
Al1.add ("abc");
Al1.add (1);  Compile times wrong,

When we instantiate al1 with the string argument type, we cannot add the int element, otherwise the compiler will complain, usually in the IDE editor, such as Eclipse, where there is an error identifier, and no type conversion is required in the FETCH element.

String value = Al1.get (0); Type conversion is not required

This is the benefit of generics.

Then the reuse of the algorithm is mainly the body now, the reuse of the method, such as the ArrayList 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 quick 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>{ 
 
  @Override public 
  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 a method, it is mainly to make the corresponding constraints on multiple parameters of the method, where the generic type parameter of the method is no longer an example, the following we mainly introduce the constraints of the type parameter.

Third, 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);//Compile error, the method CompareTo (t) are undefined for The type T. 
  return t1;  
} 

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

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

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

We can use & to segment multiple qualifiers of a type, and the Restricted keyword can only use extends. At the same time, when both interfaces and types exist, the class can only be placed first and only one, as follows:

<t extends Object&comparable&serializable> 

This article on the role of Java generics and the basic concept is small to share all the content of the people, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.