Java generic explanation (General generic, wildcard, generic interface, Generic Array, generic method, generic nesting)

Source: Internet
Author: User

Java generic explanation (General generic, wildcard, generic interface, Generic Array, generic method, generic nesting)

JDK 5.0 has long been expected, but it was changed to version when it was released. This shows that Java has changed significantly. This article describes the new features supported by JDK-Java generics.

1. Java generic

In fact, Java generic is to create a class with the type as the parameter. Just like the method of writing a class, the method is such a method (String str1, String str2). The values of str1 and str2 in the method are variable. The same is true for generics. In this way, writing class Java_Generics <K, V> is like the str1 and str2 parameters in the method.

 

Note the following when writing generic classes:

1) when defining a generic class, define the formal type parameters between "<>", for example, "class TestGen <K, V>", where "K ", "V" does not represent a value, but a type.

2) when instantiating a generic object, you must specify the value (type) of the type parameter after the class name, which must be written twice in total. For example:

TestGen <String, String> t = new TestGen <String, String> ();

3) in the generic <K extends Object>, extends does not represent inheritance. It is a type range restriction.

 

General generic

Java code
  1. Class Point {// You can write the identifier here. T is short for type.
  2. Private T var; // The type of var is specified by T, that is, by external
  3. Public T getVar () {// The type of the returned value is determined by the external
  4. Return var;
  5. }
  6. Public void setVar (T var) {// The set type is also determined by the external
  7. This. var = var;
  8. }
  9. };
  10. Public class GenericsDemo06 {
  11. Public static void main (String args []) {
  12. Point P = new Point (); // The var type is String type.
  13. P. setVar (it); // set the string
  14. System. out. println (p. getVar (). length (); // obtain the string length.
  15. }
  16. };
  17. ----------------------------------------------------------
  18. Class Notepad {// Two generic types are specified here
  19. Private K key; // The type of this variable is determined by the external
  20. Private V value; // The type of this variable is determined by the external
  21. Public K getKey (){
  22. Return this. key;
  23. }
  24. Public V getValue (){
  25. Return this. value;
  26. }
  27. Public void setKey (K key ){
  28. This. key = key;
  29. }
  30. Public void setValue (V value ){
  31. This. value = value;
  32. }
  33. };
  34. Public class GenericsDemo09 {
  35. Public static void main (String args []) {
  36. Notepad T = null; // defines two generic objects.
  37. T = new Notepad (); // The key in it is String, and the value is Integer.
  38. T. setKey (Tom); // set the first content
  39. T. setValue (20); // sets the second content.
  40. System. out. print (name; + t. getKey (); // obtain information
  41. System. out. print (, age; + t. getValue (); // obtain information
  42.  
  43. }
  44. };

    Wildcard

    Java code
    1. Class Info {
    2. Private T var; // defines generic Variables
    3. Public void setVar (T var ){
    4. This. var = var;
    5. }
    6. Public T getVar (){
    7. Return this. var;
    8. }
    9. Public String toString () {// print directly
    10. Return this. var. toString ();
    11. }
    12. };
    13. Public class GenericsDemo14 {
    14. Public static void main (String args []) {
    15. Info I = new Info (); // Use String as the generic type
    16. I. setVar (it); // set content
    17. Fun (I );
    18. }
    19. Public static void fun (Info Temp) {// can receive any generic object
    20. System. out. println (content: + temp );
    21. }
    22. };

      Restricted Generic

      Java code
      1. Class Info {
      2. Private T var; // defines generic Variables
      3. Public void setVar (T var ){
      4. This. var = var;
      5. }
      6. Public T getVar (){
      7. Return this. var;
      8. }
      9. Public String toString () {// print directly
      10. Return this. var. toString ();
      11. }
      12. };
      13. Public class GenericsDemo17 {
      14. Public static void main (String args []) {
      15. Info I1 = new Info (); // Declare the Integer generic object
      16. Info I2 = new Info (); // Declare the Float generic object
      17. I1.setVar (30); // you can specify an integer for automatic packing.
      18. I2.setVar (30.1f); // you can specify decimals for automatic packing.
      19. Fun (i1 );
      20. Fun (i2 );
      21. }
      22. Public static void fun (Info Temp) {// only the subclass of the Number and its Number can be received.
      23. System. out. print (temp + ,);
      24. }
      25. };
      26. ----------------------------------------------------------
      27. Class Info {
      28. Private T var; // defines generic Variables
      29. Public void setVar (T var ){
      30. This. var = var;
      31. }
      32. Public T getVar (){
      33. Return this. var;
      34. }
      35. Public String toString () {// print directly
      36. Return this. var. toString ();
      37. }
      38. };
      39. Public class GenericsDemo21 {
      40. Public static void main (String args []) {
      41. Info I1 = new Info (); // Declare a String generic object
      42. InfoI2 = new Info(); // Declare the generic Object of the Object
      43. I1.setVar (hello );
      44. I2.setVar (new Object ());
      45. Fun (i1 );
      46. Fun (i2 );
      47. }
      48. Public static void fun (Info Temp) {// you can only receive String or Object-type generics.
      49. System. out. print (temp + ,);
      50. }
      51. };

        The generic model cannot be transformed upwards.

        Java code
        1. Class Info {
        2. Private T var; // defines generic Variables
        3. Public void setVar (T var ){
        4. This. var = var;
        5. }
        6. Public T getVar (){
        7. Return this. var;
        8. }
        9. Public String toString () {// print directly
        10. Return this. var. toString ();
        11. }
        12. };
        13. Public class GenericsDemo23 {
        14. Public static void main (String args []) {
        15. Info I1 = new Info (); // The generic type is String.
        16. InfoI2 = null;
        17. I2 = i1; // This sentence will cause an error incompatible types
        18. }
        19. };

          Generic Interface

          Java code
          1. Interface Info {// Define the generic type on the Interface
          2. Public T getVar (); // defines the abstract method. The return value of the abstract method is of the generic type.
          3. }
          4. Class InfoImpl Implements Info {// Defines the subclass of the generic interface
          5. Private T var; // define attributes
          6. Public InfoImpl (T var) {// set the attribute content through the constructor
          7. This. setVar (var );
          8. }
          9. Public void setVar (T var ){
          10. This. var = var;
          11. }
          12. Public T getVar (){
          13. Return this. var;
          14. }
          15. };
          16. Public class GenericsDemo24 {
          17. Public static void main (String arsg []) {
          18. Info I = null; // declare an interface object
          19. I = new InfoImpl (Tom); // instantiate an object through subclass
          20. System. out. println (content: + I. getVar ());
          21. }
          22. };
          23. ----------------------------------------------------------
          24. Interface Info {// Define the generic type on the Interface
          25. Public T getVar (); // defines the abstract method. The return value of the abstract method is of the generic type.
          26. }
          27. Class InfoImpl implements Info {// Defines the subclass of the generic interface
          28. Private String var; // define attributes
          29. Public InfoImpl (String var) {// sets the attribute content through the constructor
          30. This. setVar (var );
          31. }
          32. Public void setVar (String var ){
          33. This. var = var;
          34. }
          35. Public String getVar (){
          36. Return this. var;
          37. }
          38. };
          39. Public class GenericsDemo25 {
          40. Public static void main (String arsg []) {
          41. Info I = null; // declare an interface object
          42. I = new InfoImpl (Tom); // instantiate an object by subclass
          43. System. out. println (content: + I. getVar ());
          44. }
          45. };

            Generic Method

            Java code
            1. Class Demo {
            2. Public T fun (T t) {// can receive any type of data
            3. Return t; // directly return the Parameter
            4. }
            5. };
            6. Public class GenericsDemo26 {
            7. Public static void main (String args []) {
            8. Demo d = new Demo (); // instantiate the Demo object
            9. String str = d. fun (Tom); // pass the String
            10. Int I = d. fun (30); // pass the number, automatically boxed
            11. System. out. println (str); // output content
            12. System. out. println (I); // output content
            13. }
            14. };

              Returns a generic instance using the generic method.

              Java code
              1. Class Info {// Specify the upper limit, which can only be numbers
              2. Private T var; // This type is determined by the external
              3. Public T getVar (){
              4. Return this. var;
              5. }
              6. Public void setVar (T var ){
              7. This. var = var;
              8. }
              9. Public String toString () {// override the toString () method in the Object class
              10. Return this. var. toString ();
              11. }
              12. };
              13. Public class GenericsDemo27 {
              14. Public static void main (String args []) {
              15. Info I = fun (30 );
              16. System. out. println (I. getVar ());
              17. }
              18. Public static Info Fun (T param) {// The generic type passed in or returned by the method is determined by the parameter type set when the method is called.
              19. Info Temp = new Info (); // Instantiate Info based on the input data type
              20. Temp. setVar (param); // set the passed content to the var attribute of the Info Object.
              21. Return temp; // return the instantiated object
              22. }
              23. };

                Unified input parameter types using generics

                Java code
                1. Class Info {// Specify the upper limit, which can only be numbers
                2. Private T var; // This type is determined by the external
                3. Public T getVar (){
                4. Return this. var;
                5. }
                6. Public void setVar (T var ){
                7. This. var = var;
                8. }
                9. Public String toString () {// override the toString () method in the Object class
                10. Return this. var. toString ();
                11. }
                12. };
                13. Public class GenericsDemo28 {
                14. Public static void main (String args []) {
                15. Info I1 = new Info ();
                16. Info I2 = new Info ();
                17. I1.setVar (HELLO); // set content
                18. I2.setVar (Tom); // set content
                19. Add (i1, i2 );
                20. }
                21. Public static Void add (Info I1, Info I2 ){
                22. System. out. println (i1.getVar () ++ i2.getVar ());
                23. }
                24. };

                  Generic Array

                  Java code
                  1. Public class GenericsDemo30 {
                  2. Public static void main (String args []) {
                  3. Integer I [] = fun1 (,); // returns a Generic Array
                  4. Fun2 (I );
                  5. }
                  6. Public static T [] fun1 (T... arg) {// receives variable parameters
                  7. Return arg; // returns a Generic Array.
                  8. }
                  9. Public static Void fun2 (T param []) {// output
                  10. System. out. print (receiving Generic Array :);
                  11. For (T t: param ){
                  12. System. out. print (t + ,);
                  13. }
                  14. }
                  15. };

                    Nested settings of generics

                    Java code
                    1. Class Info {// Receive two generic types
                    2. Private T var;
                    3. Private V value;
                    4. Public Info (T var, V value ){
                    5. This. setVar (var );
                    6. This. setValue (value );
                    7. }
                    8. Public void setVar (T var ){
                    9. This. var = var;
                    10. }
                    11. Public void setValue (V value ){
                    12. This. value = value;
                    13. }
                    14. Public T getVar (){
                    15. Return this. var;
                    16. }
                    17. Public V getValue (){
                    18. Return this. value;
                    19. }
                    20. };
                    21. Class Demo{
                    22. Private S info;
                    23. Public Demo (S info ){
                    24. This. setInfo (info );
                    25. }
                    26. Public void setInfo (S info ){
                    27. This.info = info;
                    28. }
                    29. Public S getInfo (){
                    30. Return this.info;
                    31. }
                    32. };
                    33. Public class GenericsDemo31 {
                    34. Public static void main (String args []) {
                    35. Demo > D = null; // use Info as the wildcard type of the Demo.
                    36. Info I = null; // Info specifies two generic types
                    37. I = new Info (Tom, 30); // instantiate the Info Object
                    38. D = new Demo > (I); // set the Info class object in the Demo class
                    39. System. out. println (Content 1: + d. getInfo (). getVar ());
                    40. System. out. println (content 2: + d. getInfo (). getValue ());
                    41. }
                    42. };

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.