Summarization and analysis of generics based on Java _java

Source: Internet
Author: User

I'm going to tell you that generics are a what. I really can't say it, this is first introduced by a problem:

  Defines a coordinate point class that requires the ability to save various types of data, such as: cosmetic, floating-point, and string types

Since variable types are initially uncertain, it is easy to think of using all types of parent classes, the object class instead

No nonsense, use code to reflect

Example 1: Using object to implement an indeterminate data type input

Copy Code code as follows:

This is the defined coordinate point class
Class Point {
Private Object x;
Private Object y;

Use object to represent an indeterminate type
Public point (Object X, object y) {
This.setx (x);
This.sety (y);
}
public void SetX (Object x) {
this.x = x;
}
Public Object GetX () {
return x;
}
public void Sety (Object y) {
This.y = y;
}
Public Object GetY () {
return y;
}

}

Test class
public class Demo {
public static void Main (string[] args) {
SYSTEM.OUT.PRINTLN ("representation coordinates with floating-point numbers:");
Point P = new Point (12.23,23.21);
This turns the object class into a double, and then automatically splits the box, two of the following
SYSTEM.OUT.PRINTLN ("x coordinates" + (Double) p.getx ());
System.out.println ("Y coordinate" + (Double) p.gety ());
System.out.println ();

System.out.println ("Representation of coordinates by integer:");
Point P2 = new Point (12, 23);
SYSTEM.OUT.PRINTLN ("x coordinates" + (Integer) p2.getx ());
System.out.println ("Y coordinate" + (Integer) p2.gety ());
System.out.println ();

SYSTEM.OUT.PRINTLN ("Coordinate with string:");
Point p3 = new Point ("latitude 29 degrees", "longitude 113 degrees");
SYSTEM.OUT.PRINTLN ("x coordinates" + (String) p3.getx ());
System.out.println ("Y coordinate" + (String) p3.gety ());
}
}

This allows you to substitute different types of data, but don't forget that the data at this point is the object type, which is the parent class of all types.

You have to be aware of what type you are passing in, and then turn it into a downward transition process to use

Although this satisfies the demand, but implicitly an unsafe factor, why is it implied?

For example, we use new Point (12.23, "latitude 29 degrees") to construct a point object

And then you use (Double) to transform it downward, what will happen?

Yes, compilation passes, but a type conversion exception occurs once it is run

It is also easy to avoid class conversion exceptions by replacing the object declaration with a fixed type declaration (for example, String x,string y) so that the error occurs at compile time

Then you can look for the wrong place to make the change

But in that case, we won't be able to meet our needs.

In order to achieve the goal of not having security risks and substituting various data types, those cows introduced the concept of generics in JDK1.5.

Let's see how to overwrite the above code with generics.

Instance 2: Generic class

Copy Code code as follows:

Class Point<t> {
Here we use T to indicate the type of uncertainty
Private T x;
Private T y;
Public point (t X, t y) {
This.setx (x);
This.sety (y);
}
Public T GetX () {
return x;
}
public void SetX (T x) {
this.x = x;
}
Public T GetY () {
return y;
}
public void Sety (T y) {
This.y = y;
}
}

public class Demo {
public static void Main (string[] args) {
SYSTEM.OUT.PRINTLN ("representation coordinates with floating-point numbers:");
After overwriting with generics, using data does not need to be done down-conversion processing
point<double> p = new point<double> (12.23,23.21);
SYSTEM.OUT.PRINTLN ("x coordinates" + P.GETX ());
System.out.println ("y coordinate" + p.gety ());
System.out.println ();

System.out.println ("Representation of coordinates by integer:");
point<integer> P2 = new Point<integer> (12, 23);
SYSTEM.OUT.PRINTLN ("x coordinates" + P2.GETX ());
System.out.println ("y coordinate" + p2.gety ());
System.out.println ();

SYSTEM.OUT.PRINTLN ("Coordinate with string:");
point<string> p3 = new Point<string> ("latitude 29 degrees", "longitude 113 degrees");
SYSTEM.OUT.PRINTLN ("x coordinates" + P3.GETX ());
System.out.println ("y coordinate" + p3.gety ());
}
}

After using generics, you can reduce the presence of security risks

If we deliberately pass in a different data type at this time:

point<double> p = new Point<double> ("latitude 29 degrees", 12.22);

Then, the error occurs at compile time

Although generics are defined, if you do not use a generic mechanism in the constructor, then it treats the data as Object

The main purpose of this is to be compatible with JDK1.4 old code, such as

Point P = new Point (22.11,23.21);

The end result is the same, but the warning message is prompted at compile time

Example 3: Generic method

As you can see from the example above, once the object type is explicitly defined in the constructor, the same type is used in the entire class

The most typical example is the application of the set frame, such as:arraylist<integer> al = new Arraylist<integer> ();

At this point, all of the object types that are operating in Al are integers.

However, sometimes we don't want to fix dead objects, but we want to be more flexible in using generic technology.

This is the time to try the generic method

Copy Code code as follows:

Generic is no longer defined after the class name
Class Print {
Defining generics in a method
Public <T> void Print (T-t) {
System.out.println (t);
}

Public <E> Void Show (E e) {
System.out.println (e);
}
}

public class Demo {
public static void Main (string[] args) {
Print P = new print ();
P.print (12);
P.print ("Hello");
P.show (New Integer (33));
P.show (23);
}
}

In fact, there's nothing much different from using object objects in a method.

What's more, after JDK1.5 added the automatic unboxing function, eliminating the need for downward transition of trouble

Instance 4: Generic interface

Copy Code code as follows:

Definition of a generic interface
Interface inter<t>
{
public void print (T-t);
}

Implementation Mode one:
Class InterDemo1 implements Inter<string> {
public void print (String t) {
System.out.println ("Print:" + t);
}
}

Implementation Mode two:
Class Interdemo2<t> implements Inter<t> {
public void print (T-t) {
System.out.println ("Print:" + t);
}
}

Class Demo {
public static void Main (string[] args) {
InterDemo1 id1 = new InterDemo1 ();
Id1.print ("Hello");
Interdemo2<integer> id2 = new interdemo2<integer> ();
Id2.print (New Integer (23));
}
}

There are two ways to implement a generic interface, one of which is to specify the generic type at the time of implementation

The other is that generics are still used, and the generic type is determined at the time of construction

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.