Java generic learning and practice (1), java generic

Source: Internet
Author: User

Java generic learning and practice (1), java generic
Introduction

After JDK1.5, generic models were introduced, which was hard to understand at the beginning. After learning them slowly, there are some gains. In conclusion, they can not only deepen your understanding, but also help others.

Due to my limited level, it is inevitable that something is wrong. please correct me. Not much nonsense. The following is the official start.


To more intuitively describe the generic model, we assume that a driver is driving. We need three classes: Driver, Ford, and Buick ).

First version

The first version of this Code is as follows:

public class Buick {        public void run(){        System.out.println("buick run");    }        public void autoRun(){        System.out.println("buick auto-run");    }    }
public class Ford {        public void run(){        System.out.println("ford run");    }        public void fly(){        System.out.println("ford fly");    }}
Public class Driver {private Object car; public void drive (Object car) {this. car = car; if (car instanceof Buick) {System. out. println ("I am driving a" + car); (Buick) car ). run ();} else if (car instanceof Ford) {System. out. println ("I am driving a" + car); (Ford) car ). run () ;}} public Object getDrivingCar () {return car;} public static void main (String [] args) {Driver driver1 = new Driver (); driver1.drive (new Ford (); Driver driver2 = new Driver (); driver2.drive (new Buick ());//... execute Other business logic/** get a Ford car driving 1 execute the fly Method */(Ford) driver1.getDrivingCar ()). fly ();/** get the Buick driver 2 and execute the autoRun Method */(Buick) driver2.getDrivingCar ()). autoRun ();}}


Briefly describe the three classes. Both the Buick class and the Ford class contain the run method, the Buick class has the autoRun method, and the Ford class has the fly method. The Driver class has a drive method, a getDrivingCar method, and an internal attribute car. The main static method is a demo.


The preceding demo shows that when the drive method of the Driver instance is called, the actual parameters are transformed to the Object upwards. When the getDrivingCar method is called, we also need to switch down to a specific car class to call its specific method. So what is the problem with this method?

The problem is obvious. The parameter type of the drive method is the same as that of the getDrivingCar method, but because different cars are supported, transition to Object type (not defined as a specific Buick type or Ford type), so that the external calls to getDrivingCar will return a generalized Object, thus losing the characteristics of a specific class, forced External type conversion is required. This display forced conversion method can easily generate a ClassCastException (this exception will be thrown when the code is executed when driver2 is written as driver1 accidentally), and this programming error cannot be found during compilation, however, it can only be detected during running, and hidden bugs may occur. In addition, this method is unreasonable, and the Driver class is too difficult to use. You need to be careful with the external code to prevent errors. For example, you can use instanceof to judge before force conversion. Is there any better way?

Version 2

The second version of the Code is as follows (only modify the Driver Class ):

Public class Driver <T> {private T car; public void drive (T car) {this. car = car; if (car instanceof Buick) {System. out. println ("I am driving a" + car); (Buick) car ). run ();} else if (car instanceof Ford) {System. out. println ("I am driving a" + car); (Ford) car ). run () ;}} public T getDrivingCar () {return car;} public static void main (String [] args) {Driver <Ford> driver1 = new Driver <Ford> (); driver1.drive (new Ford (); Driver <Buick> driver2 = new Driver <Buick> (); driver2.drive (new Buick ());//... execute Other business logic/** get the Ford car driving 1 execute the fly Method */driver1.getDrivingCar (). fly ();/** get the driver 2 drive Buick and execute the autoRun Method */driver2.getDrivingCar (). autoRun ();}}

<T> used in the Driver class Declaration, that is, generic T. You can understand the T type to represent any specific type. Both the parameter type of the drive method and the return value type of the getDrivingCar method and the private property car are T types. So what are the benefits of doing so?

From the Demo code of the main method, we can see that when instantiating the Driver class, we need to specify the specific T type (Buick in Ford and driver2 in driver1 ). After instantiation, the return type of the getDrivingCar method is also the corresponding type, so that you can directly call a method of a specific type.

Compare the first version of the Driver class with the others version of the Driver class. You only need to specify the specific T type when instantiating the class, and do not need to perform forced type conversion in subsequent operations, this reduces the possibility of errors and improves code security.

Using generic T, it is easy to unify the types of the drive method parameter type, getDrivingCar method return value type, and private attribute car type, without losing its specialization (unlike the first version declaring car as the Object type), there is no additional code cost, and the class structure looks clear and clear. For external users, the usage threshold is low, so there will be no errors of the type accidentally (or impossible if possible). If the error type is specified, an error will be prompted during compilation)

The above example demonstrates the basic usage of generics. With generics, it is easy to declare a uniform type between the member variables of the class, method parameters, or method return values without losing the specialization of the type (in the class definition, it is a generic type, but the specific type must be specified during instantiation)


Actual contact information

Now you should have a basic understanding of generics. The following is an example of an instance project to further illustrate the problem.

Projects generally require paging classes. The simplified version is as follows:

/*** <Simple paging class> */public class SimplePage {/** number of records displayed on each page */private int numPerPage; /** total number of records */private int totalCount;/** current page */private int pageNum ;//... omit other methods}
/***** <Pagination class with content> */public class Pageable <E> extends SimplePage {/***** content on this page */private List <E> list; /*** <set content> * @ param list */public void setList (List <E> list) {this. list = list;}/*** <get content> * @ return */public List <E> getList () {return list ;}}

SimplePage: simple paging class that contains basic member attributes such as the number of records and total number of records displayed on each page of the current page.

Pageable: the pagination class of business data. It inherits from the simple paging class and carries the data information on this page.

For example, to query User information by PAGE, assume that the User class encapsulates User information. The Code is as follows:

Pageable <User> pageInfo = new Pageable <User> ();//... obtain User information by PAGE, and call the setList method to put User information into the pageInfo instance/** get userList elsewhere for other business operations */List <User> userList = pageInfo. getList ();

It is very simple to use. Today we will be here, and it will be available soon.

The code word is not easy. indicate the source for reprinting.

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.