JavaSE: Generic Summary

Source: Internet
Author: User

JavaSE: Generic Summary

For the summary of jdbc, I would like to wait for a while before summing up. Just like my summary and review of the JavaSE section, I feel this is a benefit, you will have a deeper understanding of this knowledge. For example, when I was studying jdbc, I had a lot of confusion in the usage of generics. Now, I have a deeper understanding and understanding.

Generic (Generics ):

Appearance of generics: since JDK1.5
I think the explanation given by DW in IBM is very good:
Generics is a technique of programming language. It refers to parameterization of data types in a program. In essence, Generics abstracts the Data Types of the program and extends the expression ability of the language, at the same time, it supports more powerful code reuse.
Thoughts spread:
Java Abstract classes. Is the interface just like this? abstract classes, extend the language expression capability, and more powerful support for code reuse.

Summary:
Generics --> abstract the data type (reference type)
Abstract Class/interface --> abstract a Class
Commonalities: abstraction.
Advantage: Improves code reusability.

Ps: This is a summary ....!

Why should I use generics?

We want to add some student IDs to a List:

List list = new ArrayList (); list. add (1, 100); list. add (1, 101); list. add (102); // However, I want to add my name to the list. add (Lei Feng); // Let's traverse and see the student ID for (Object object: list) {int sId = (Integer) Object; // force type conversion and automatic unpacking System. out. println (sId );}

I found that an error was reported during compilation because Lei Feng was naughty and ClassCastException.

To solve this problem of data destruction and forced type conversion, we have a generic type.
After using the generic type:

List
  
   
List = new ArrayList <> (); // since JDK1.7 list. add (1, 100); list. add (1, 101); list. add (102); // However, I want to add my name to the list. add (Lei Feng); // Let's traverse and see the student ID for (Integer sid: list) {System. out. println (sId );}
  

I found that Lei Feng, a naughty classmate, could not be added. An error was reported during compilation.

Generic usage:
1. Use generics in the collection
2. Custom generic classes, generic interfaces, and generic methods
3. Relationship between generics and inheritance
4. wildcard characters

Set to use generics:
I don't want to talk much about the specifics. I believe everyone will have a deep understanding of it when using it. In particular, like me, you have to always think about why such a warning should appear. As a result, no warning is given for all my codes.
Custom generic classes:
You can refer to the use of generic classes in the set. If you do not know, you can refer to the Integration Section of the API.

Public class Order
  
   
{Private int id; private String name; private T t; List
   
    
List = new ArrayList
    
     
(); Public void add (T t) {list. add ();} public void setT (T t) {this. t = t;} public T getT () {return t;} public void setId (int id) {this. id = id;} public void getId () {return id ;}... // The get method of the name attribute is the same as that of the set method .}
    
   
  

The user-defined interface is similar.

Generic method:

In the above example, add a generic method:

Public class Order
  
   
{Private int id; private String name; private T t; List
   
    
List = new ArrayList
    
     
(); Public void add (T t) {list. add ();} public void setT (T t) {this. t = t;} public T getT () {return t;} www.bkjia.com public void setId (int id) {this. id = id;} public void getId () {return id ;}... // The get method of the name attribute is the same as that of the set method. // Generic method public
     
      
E getE (E e) {return e ;}}
     
    
   
  

Pay attention to the declaration of generic methods. Unlike generic classes, generic interfaces are different.

Inheritance relationship between generics and classes:

    Object obj = null;    String str = hellowrold;    obj = str;

In this way, we know that you can compile, run, and use polymorphism (upward transformation). Let's look at the following:

    List list = null;    List
   
     list2 = new ArrayList<>();    list2.add(zhangsan);    list2.add(lisi);    list = list2;
   

Mismatch is reported during compilation, and the type does not match.
--> If Class A is A subclass of Class BListNoListSub-interface
--> List2 and list do not have an inheritance relationship
--> Classes with Generics do not have inheritance relationships. They are same-level relationships.

--? What should I do if I want to add another type to the Object?

List
It can be understood as a relationship between less than or equal
There is also a way to use (not to address the above issues ):
List
It can be understood as a relationship greater than or equal

Reference the above sentence:

Classes with Generics do not have inheritance relationships. They are same-level relationships.

--> Is there a class that is the parent class of all generic classes?

Wildcard :?

List, ListYes List Subclass

? extends A :It can store A and its sub-classes or sub-interfaces.
? super B :It can store B and its parent class or parent interface

Note: A class that uses wildcards can only be written but cannot be read (except null)

To sum up, you need to understand and pay attention to the following points:
1. The parameterization mentioned above is actually the meaning of generics.
2. When an Object is instantiated, the generic type is not specified. The default value is Object.
3. Generic references cannot be assigned values to each other.
4. The generic elements added to the set must be consistent with the specified generic type.
5. Do not use generics in static methods
Understanding: a static method exists before an object and can be called directly through the class name. The generic type is not specified during the call, so the generic type cannot be used.
6. You cannot use generics in cathch. An error is reported during compilation.
7. Subclass derived from generic classes. Subclass must be specific

Core Idea of generics:

Restrict data in a class or interface to a specific data type

The following is an example of generic usage:
When designing a class, users often use class associations. For example, a person can define an attribute of information, however, a person may have a variety of information (such as contact information and basic information), so the type of this information attribute can be declared through generics, And then you only need to design the corresponding information class.

interface Info{}
Public class Contact implements Info {private String address; private Stirng phone; private String zipCode; // No parameter constructor // a parameter constructor // get and set method // toString () method}
Public class Inroduction implements Info {private String name; private String sex; private int age; // same as above}
class Person  { private T info; public Person(T info){ this.info = info; } //get and set method //toString()} 
public class GenericPerson{ public static void main(String[] args){ Person  per = new Person<>(new Contact(Beijign, 88888888888, 000000)); } System.out.println(per); Person  per2 = new Person<>(new Introduction(Jay, M, 23)) System.out.println(per2);}  

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.