JAVA basics-general summary

Source: Internet
Author: User

JAVA basics-general summary
Concept:

Generics are new features of Java SE 1.5. The nature of generics is parameterized, that is, the Data Type operated is specified as a parameter. This type of parameter can be used to create classes, interfaces, and methods, which are called generic classes, generic interfaces, and generic methods. The advantage of introducing generics in Java is that it is secure and simple.


Common characters of the generic type mean:

? Indicates an uncertain java type.
T indicates the java type.
K v represents the Key Value in the java Key Value.
E Represents the Element.


The following is a good example on cnblog.

It's really good. I wrote it for a long time. When I saw it, I immediately deleted it ~

General generic

  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. };

    Wildcard

    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"); // sets the 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

      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.

        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

          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

            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.

              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

                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"); // sets the content
                18. I2.setVar ("Tom"); // set the 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

                  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

                    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. };
                      Generic Erasure

                      Due to the type erasure problem, all generic type variables are replaced with the original type. This leads to a problem. Since all are replaced with the original type, why do we not need to perform forced type conversion when obtaining it? Let's take a look at the ArrayList and get methods:

                      public E get(int index) {    RangeCheck(index);    return (E) elementData[index];}
                      We can see that the conversion is strong according to the generic variables before return. Assume that the generic type variable is Date. Although the generic information is erased, the (E) elementData [index] is compiled into (Date) elementData [index]. Therefore, we do not need to perform strong conversion on our own.


                      Generic And Difference

                      And It contains a new concept of JAVA5.0. Because of their appearance, many people misunderstand their purposes:

                      1.

                      First, you can easily misunderstand it as a set of all classes inherited from T. This is a big mistake.

                      I believe you have seen or used List. Right? Why is it wrong to understand it as a set? If it is understood as a set, why not use List? ? So It is not a set, but the meaning of a subclass of T. Remember that it is a single and single type. The problem arises because of the uncertainty of the connected type, therefore, it is impossible to add elements by adding. Why do you still think "add (T)" is not working? Because Is a subclass of T. containers that can be placed in the subclass may not be placed in the superclass, that is, they may not be placed in T.
                      2.

                      It is easier to use here, no So many restrictions here mean that a class with T class as the lower limit is simply a super class of T class. But why can I add (T? Because a container that can be put into a certain type can certainly be placed into its subclass, the concept of polymorphism.



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.