Java Generics supplements

Source: Internet
Author: User
Tags java se

First on the Baidu Encyclopedia explanation

Generics are a new feature of Java SE 1.5, and the nature of generics is a parameterized type, meaning 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 secure.
In the case of Java SE 1.5, without generics, the "arbitrariness" of arguments is implemented by reference to type object, and the disadvantage of "arbitrariness" is to make explicit coercion of type conversions, which require the developer to be able to predict the actual parameter type. In the case of coercion of type conversion errors, the compiler may not prompt for an error and an exception occurs at run time, which is a security risk.

Well, I know that if the first release of the generics directly lost, what is this???
Understanding the generic first step understanding type information erasure.

1. Simple generics
Type information erasure, two examples

@Test Public voidtestgeneric () {List<String> List1 =NewArraylist<string>(); List<Integer> List2 =NewArraylist<integer>(); System.out.println ("List1 Type" +List1.getclass ()); System.out.println ("List2 Type" +List2.getclass ());} List1 Type class Java.util.ArrayListlist2 type class Java.util.arraylist@test Public voidTestGeneric1 () {List List=NewArrayList (); List.add ("XYZ"); List.add (100);  for(inti = 0; I < list.size (); i++) {String name=(String) list.get (i); System.out.println ("Name:" +name); }}name:xyzjava.lang.classcastexception:java.lang.integer cannot is cast to java.lang.String

This example is obviously not a problem during the compile phase, and the execution phase is hung out.
This is an inappropriate example: fish and cats can not be put into a basket, put in nothing, take out also want to get fish, that is too simple.
So it is necessary to avoid this situation, if there is a cat in the basket, do not put the fish, if there are fish also let the cat far point, this is not explained the generics.

See the definition of the list interface in detail.

2. Generic interface

Take the list interface above for example

Public interface list<e> extends collection<e> {...}

public class Arraylist<e> extends abstractlist<e>
Implements List<e>, Randomaccess, Cloneable, java.io.Serializable
{...}

Such a generic interface is suitable for the Factory mode, this left a pit here, design mode I have put that, I hope to finish the series ... (Procrastination patients can't afford to hurt, design patterns I absolutely finished, give yourself a little confidence, always have a bit of persistence)

3. Generic methods
To make a declaration of a generic method, a class that has a generic method can be a generic class, or it may not be a generic class, but it doesn't really matter what the class is.
That is the popular words, you are strong to your strong ...

 Public class generictest {    publicvoid  printclassinfo (T t) {        System.out.println ( T.getclass (). GetName ());}    } @Testpublicvoid  TestGeneric2 () {    new  generictest ();    Generictest.printclassinfo ("String");    Generictest.printclassinfo (new Integer ("123"));    Generictest.printclassinfo (generictest);} Java.lang.Stringjava.lang.Integercom.test.GenericTest

Such a class can both pass in string Integer and have a custom type good magic method overloads have no

4. Generic class

 Public classGenericclass<t> {     PublicT getobj () {returnobj; }     Public voidsetobj (T obj) { This. obj =obj; }    PrivateT obj;} @Test Public voidtestGeneric3 () {Genericclass genericclasstest=NewGenericclass (); Generictest.printclassinfo ("String"); Generictest.printclassinfo (NewInteger ("123")); Generictest.printclassinfo (generictest);} Testgeneric

Generic boundary
A method that can be called with unbounded generics, which is a method that can be called with object
Without restricting boundaries, that's object.

Java generic programming uses the extends keyword to specify the upper bounds of the generic parameter type (which is also described using the Super keyword to specify the bottom bounds of the generic), that is, generics can only be applied to subclasses of classes or interfaces after the extends keyword.
The boundaries of Java generic programming can be multiple, declared using such <t extends A & B & c> syntax, where only one is a class, and only the first one behind the extends is the class, and the others are only interfaces (and classes/ The extends meaning in the interface is different).
After a generic boundary is used, the generic object can use the public member variables and methods in the bounding object.

@Test Public voidTestGeneric4 () {Generateanimal dog=NewGenerateanimal (NewDog ()); Dog.getname ();} Public classDogImplementsAnimal {@Override PublicString GetName () {System.out.println ("Dog"); return"Dog"; }} Public InterfaceAnimal {String getName ();} Public classGenerateanimal<textendsAnimal> {    PrivateT T; Generateanimal (T t) { This. T =T; }     PublicString GetName () {returnT.getname (); }}

Generic wild-wildcard characters

@Test Public voidtestGeneric5 () {Fruit<String> F1 =NewFruit<> ("Ordinary as I"); Fruit<Integer> F2 =NewFruit<> (77); Fruit<Double> F3 =NewFruit<> (22.1);    GetData (F1);    GetData (F2);    GetData (F3); //Getfruitdata (F1); compilation issuesGetfruitdata (F2); Getfruitdata (F3);}Private voidGetData (fruit<?>f) {System.out.println ("Fruit:" +f.getdata ());}Private voidGetfruitdata (fruit<?extendsNumber>f) {System.out.println ("Fruit:" +f.getdata ());} Fruit: Ordinary as I Fruit:77Fruit:22.1Fruit:77Fruit:22.1@Test Public voidtestGeneric6 () {Fruit<String> F1 =NewFruit<> ("Ordinary as I"); Fruit<Integer> F2 =NewFruit<> (77); Fruit<Double> F3 =NewFruit<> (22.1); //Getfruitsupperdata (F1);//Compilation Issues//Getfruitsupperdata (F3);//Compilation IssuesGetfruitsupperdata (F2);}Private voidGetfruitsupperdata (fruit<?SuperInteger>f) {System.out.println ("Fruit:" +f.getdata ());}

Summarize

About generics these are also similar, in my understanding, Java is a strong type of language, and generics, so that the parameter type is changeable, of course, the above example and the actual application of the generic is far worse, I hope to be more integrated application of generics.

Java Generics supplements

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.