Java Generic Instance detailed _java

Source: Internet
Author: User

The easiest way to understand Java generics is to think of it as a handy syntax that saves you from some of the actions on Java type conversions (casting):

      list<apple> box = ...;
 	Apple Apple = box.get (0);

The above code itself has made it clear that box is a list of Apple objects. The Get method returns an instance of an Apple object that does not require a type conversion. Without generics, the code above needs to be written like this:

      List box = ...;
 	Apple Apple = (apple) box.get (0);

Obviously, the main benefit of generics is that the compiler retains the type information of the parameter, performs type checking, and performs type conversion operations: The compiler guarantees that these types of conversions are absolutely correct. Rather than relying on programmers to remember object types and perform type conversions-which can cause the program to run unsuccessfully, it is difficult to debug and resolve, and the compiler can help programmers to force a large number of type checks at compile time to discover errors.

Composition of a generic type

The concept of a type variable is derived from the composition of the generic type. According to the Java language Specification, a type variable is an unrestricted identifier that arises from the following situations:

Generic class declaration
Generic interface Declaration
Generic method declaration
Generic Constructor (constructor) declaration

Generic classes and Interfaces

If there is one or more type variables on a class or interface, it is generic. Type variables are defined by angle brackets and are placed after the class or interface name:

Public interface List<t> extends collection<t> {
	...
	}

Simply put, the role of a type variable acts as a parameter that provides the compiler with the information it uses to type check.

Many classes in the Java class Library, such as the entire collection framework, have been modified in a generic format. For example, the list interface we used in the first paragraph of the above code is a generic class. In that code, box is a List<apple> object, which is an instance of a class implementation with a list interface with an Apple type variable. The compiler uses this type variable parameter to automatically type conversions when the Get method is invoked and returns an Apple object.

In fact, the new generic tag, or the Get method in the list interface, is this:

T get (int index);

The Get method actually returns an object of type T, which is a type variable in the list<t> declaration.

Generic methods and constructors (constructor)

Very similar, if one or more type variables are declared on the method and constructor, they can also be generalized.

public static <t> T GetFirst (list<t> List)

This method will accept an argument of the list<t> type, returning an object of type T. You can use either the generic class provided in the Java class Library or your own generic class. Type-safe Write data ... The following code is an example, we create a list<string> instance, and then load some data:

list<string> str = new arraylist<string> ();
 	Str.add ("Hello");
 	Str.add ("World.");

If we try to mount another object in list<string>, the compiler prompts for an error:

Str.add (1);

Type-safe read data ...

When we use the List<string> object, it always guarantees that we get a String object:

String myString = str.get (0);

Traversal: Many classes in the class library, such as ITERATOR<T>, are enhanced and are generalized. The iterator () method in the List<t> interface now returns the Iterator<t>, and the object returned by its T next () method does not require type conversion, and you get the correct type directly.

for (iterator<string> iter = Str.iterator (); Iter.hasnext ();) {
	String s = iter.next ();
	System.out.print (s);
	}

With foreach, the "For each" syntax also benefits from generics. The preceding code can write this:

for (String s:str) {
	System.out.print (s);
	}

This is easy to read and easy to maintain.

Automatic Encapsulation (autoboxing) and automatic unpacking (autounboxing) , when using Java generics, autoboxing/autounboxing these two features are automatically used, as in the following code:

list<integer> ints = new arraylist<integer> ();
 	Ints.add (0);
	Ints.add (1);
 	
	int sum = 0;
	for (int i:ints) {
 	sum = i;
 	}

However, one thing you should understand is that encapsulation and marshaling can lead to performance losses, all of which are used sparingly by the General Assembly.

Generics are a new feature of the Java SE 1.5, the essence of which is a parameterized type, which means that the data type being manipulated is specified as a parameter. This type of parameter can be used in the creation of classes, interfaces, and methods, called generic classes, generic interfaces, and generic methods, respectively.

The benefits of introducing generics into the Java language are simple and safe.

Before the Java SE 1.5, without generics, the argument is "arbitrary" by reference to type object, and the disadvantage of "arbitrariness" is to do explicit coercion of type conversions, which require the developer to be able to predict the actual parameter types. In the case of coercion type conversion errors, the compiler may not prompt for an error and the exception occurs at run time, which is a security risk.

The benefit of generics is to check type safety at compile time, and all casts are automatic and implicit, increasing the reuse rate of code.

Generics also have some rules and restrictions in use:

1. A generic type parameter can only be a class type (including a custom class) and cannot be a simple type.

2. The same generic type can correspond to multiple versions (because the parameter types are indeterminate) and different versions of generic class instances are incompatible.

3, the generic type parameter can have more than one.

4, the generic type of parameter can use the extends statement, for example. Become accustomed to being "bounded type".

5. The parameter type of the generic type can also be a wildcard character type. For example Class ClassType = Class.forName (java.lang.String);

Generics also have interfaces, methods, and much more, and it takes a lot of effort to understand mastery and proficiency in application. Here are two examples of what I've learned about generics (based on impressions), the same functionality, one that uses generics, one that's not used, and by contrast, you can quickly learn generic applications and learn to basically learn the generic 70% content.

Example one: The generic type is used

public class gen﹤t﹥{
private T OB;//define Generic member variable public

Gen (T ob) {
this.ob = OB;
} public

T Getob () {return
ob;

the actual type of the public void Setob (t ob) {
this.ob = ob.
} public

void Showtyep () {
System.out.println ("t) is : "+ Ob.getclass (). GetName ());
}
}

public class Gendemo {public
static void Main (string[] args) {
//define an Integer version of the generic class Gen
Gen﹤integer﹥into B=new Gen﹤integer﹥ ();
Intob.showtyep ();
int i= Intob.getob ();
System.out.println ("value=" + i);

System.out.println ("----------------------------------");

Defines a String version of the generic class Gen
gen﹤string﹥strob=new Gen﹤string﹥ ("Hello gen!");
Strob.showtyep ();
String S=strob.getob ();
System.out.println ("value=" + s);
}

Example two: not using generics

public class Gen2 {
private Object ob;//define a Universal type member public

Gen2 (Object ob) {
this.ob = ob;
}

Publi C Object Getob () {return
ob.
} public

void Setob (Object ob) {
this.ob = ob;

The actual type of Howtyep () {
System.out.println ("t) is:" + ob.getclass (). GetName ());
}

public class GenDemo2 {public
static void Main (string[] args) {
//define an integer version of the class Gen2
Gen2 Intob = new Ge N2 (new Integer);
Intob.showtyep ();
int i = (Integer) Intob.getob ();
System.out.println ("value=" + i);

System.out.println ("----------------------------------");

Defines a string version of the class Gen2
Gen2 strob = new Gen2 ("Hello gen!");
Strob.showtyep ();
string s = (string) Strob.getob ();
System.out.println ("value=" + s);
}

Run Result:

Two examples run demo results are the same, the console output results are as follows:

The actual type of T is:

Java.lang.Integer

Value= 88

----------------------------------

The actual type of T is: java.lang.String

Value= Hello gen!

Process finished with exit code 0

See this, the basic generic application and code reading will not be a problem.

The above is the Java Generic example analysis, learning Java generics friends can refer to.

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.