Dark Horse programmer: Generic

Source: Internet
Author: User

---------------------Android Training,Java TrainingWe look forward to communicating with you!
---------------------

 


Generic: a special type that delays the operation of a specified type.CodeDeclare and instantiate classes or methods.
Generic Format: <data type>

Benefits of generics:
1: Solve the possible classcastexception problem during the runtime before the compilation.
2: the yellow line is removed and optimized.ProgramDesign.

3: You do not need to perform forced type conversion. Avoid type conversion exceptions.

Java generic parameters can only represent classes and cannot represent individual objects. Because the actual types of Java generic type parameters are eliminated during compilation, the type of the type parameters cannot be known at runtime. The Java compiler automatically adds the type conversion encoding when compiling generics, so the running speed will not be accelerated by the use of generics. Java allows constraints on some generic type parameters, including the following two forms (assuming T is a generic type parameter, c
Is a general class, generic class, or generic type parameter): T implements interface I. T is C, or inherits from C. A generic class cannot implement the throwable interface.


Example of generics:

 
Import Java. util. arraylist; import Java. util. iterator; public class genericdemo {public static void main (string [] ARGs) {arraylist <string> array = new arraylist <string> (); array. add ("Haha"); array. add ("hehe"); array. add ("Xixi"); // array. add (20); // here you have to add a clear data type to the iterator object. Iterator <string> it = array. iterator (); While (it. hasnext () {// string S = (string) it. next (); string S = it. next (); system. out. println (s);} system. out. println ("*****************"); // string [] strarray = new string [3]; // strarray [0] = "Haha"; // strarray [1] = "hehe"; // strarray [2] = 20 ;}}

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.