Java core technology -01-talk about generics

Source: Internet
Author: User

Generics are important in both real-world development and interviews, so let's talk about it today.

1, what is a generic type

The essence of generics is to control the type of formal parameter restrictions by the different types specified by generics for parameterized types.

Give me an example!

We want to define a set that can only hold integers, how to write?

List List = new ArrayList ();

Is that right? Not really, so we can add the task data type to the list

So this time, the solution is to use generics, so you can write

list<integer> list = new arraylist<> ();

With parameterized types, you can limit the types that list can add

2, generic feature, valid only for compilation period, invalid during runtime (generic erase)

Let's see if these two collections are of the same type?

List List1 = new arraylist<> ();

List list2 = new arraylist<> ();

Obviously, during compilation, two collections have a good control over the data types that are added.

However, during run time, this type is erased. Let's do an experiment and get this conclusion.

public static void Main (string[] args) {

Listlist1 = new arraylist<> ();

List list2 = new arraylist<> ();

System.out.println (list1.getclass () = = List2.getclass ());

}

Can try the results, I packed the tickets, the result is true

3, attention.

A generic parameter type can only be a reference type, not a basic data type, such as an int

4, use of generics

4.1 Generic class

public class Generictest {

public static void Main (string[] args) {

GENERICCLASSG1 = new genericclass< ();

G1.setkey (1);

System.out.println (G1.getkey ());

}

}

Class genericclass{

Private T key;

public void Setkey (T key) {

This.key = key;

}

Public T GetKey () {

return this.key;

}

}

4.2 Generic interface

Interface genericinterface{

Public T getNext ();

}


Java core technology -01-talk about generics

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.