Java from basic knowledge (eight) generics

Source: Internet
Author: User
Tags java se

1. What is a generic type?

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. The benefit of generics is that it checks for type safety at compile time, and all casts are automatic and implicit, to increase the reuse rate of code 2, generic type parameters can only be class types (including custom classes) and cannot be simple typesall generic method declarations have a type parameter declaration part (delimited by angle brackets), which is part of the type parameter declaration before the method return type (<E> in the following example)A generic type parameter can have multiple generic parameter types that can use extends statements, such as <t extends Superclass>. A parameter type that is customarily called a "bounded type" generic can also be a wildcard type. For example class<?> ClassType = Class.forName ("java.lang.String"); 3, generic principle (Java generics in-depth understanding)
 PackageCom.classTest.generic; Public classgenericordination { Public Static voidMain (string[] args) {Box<String> box =NewBox<string> ("STR"); User User=NewUser (); User.setname ("User"); User.setage (12); Box<User> Box1 =NewBox<user>(user); System.out.println (Box.getclass ()= = Box1.getclass ());//true    }}classBox<t> {    PrivateT data;  PublicBox () {} PublicBox (T data) { This. data =data; }     PublicT GetData () {returndata; }}classUser {PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; } @Override PublicString toString () {return"user{" + "name=" + name + ' \ ' + ", age=" + Age + '} '; }}

The above structure is because all generic information will be erased ,list<string> and List<user> types during compilation, and will become a List type after compilation (original type). Generics in Java are basically implemented at the compiler level, which is why Java generics are called Pseudo generics.

4. Generic classes and Methods (Java Summary series: Java generics)

 Public classGenerictest { Public Static voidMain (string[] args) {Box<String> box =NewBox<string> ("Corn"); System.out.println ("Name:" +box.getdata ()); User User=NewUser (); User.setage (1); User.setname ("Sun"); Box<User> Box1 =NewBox<user>(user);    System.out.println (Box1.getdata (). toString ()); }}

5. Type wildcard character (with? logo)

 Public classGenerictest { Public Static voidMain (string[] args) {Box<String> box =NewBox<string> ("Corn"); User User=NewUser (); User.setage (1); User.setname ("Sun"); Box<User> Box1 =NewBox<user>(user);        GetData (box);            GetData (Box1); }     Public Static voidGetData (box<?>data) {System.out.println ("Data:" +data.getdata ()); }}

7. Type wildcard upper limit and type wildcard lower limit (implemented by extends keyword)

 public  class   generictest { public  static  void   main (string[] args) {B Ox  <Integer> box = new  box<integer> (123); Box  <Long> box1 = new  box<long> (123l         public  static  void  getData (box<? extends  Number> data) {System.out.println ( "Data:" + D    Ata.getdata ()); }}

box<? Extends number> restricts the passing parameter type to the number class or its subclasses, and if the generic type is string or user, the compilation error is reported, thus achieving a valid restriction on generics.

Java from basic knowledge (eight) 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.