简体   繁体   中英

How to understand this use of Java generics

In my study book, there's this example:

import java.util.*;
public class RentalGeneric<T> {

  private List<T> rentalPool;

  private int maxNum;
  public RentalGeneric(int maxNum, List<T> rentalPool) {

  this.maxNum = maxNum;
  this.rentalPool = rentalPool;
}
public T getRental() {
  return rentalPool.get(0);
}
  public void returnRental(T returnedThing) {
    rentalPool.add(returnedThing);
  }
}

I find it strange that it compiles, since there is no definition of Class<T> . What is the story about this? It says in my book that T is for the type parameter but how do I know when to use it?

You could use it to rent cars, bikes ... You could use it directly like this:

RentalGeneric<Car> carRental = new RentalGeneric<Car>(10, aList);

Then when you'll do getRental it'll return you a Car object. And you'll be able to put back a Car with returnRental(aCar);

Or you could create a CarRental class extending RentalGeneric<Car> .

Same thing goes for whatever object you would like to rent.

T is generic Type here. It will be initialized while creating Object of RentalGeneric class.

RentalGeneric<Double> rgS =new RentalGeneric<Double>(10, new ArrayList<Double>());
RentalGeneric<Integer> rgS =new RentalGeneric<Integer>(10, new ArrayList<Integer>());

You are right, there is no direct definition of T in your code. It is however can be found at runtime outside this code. Indeed somewhere you create instance of your list. When you do it you have to supply the type information, eg

List<String> mylist = new ArrayList<String>();

Here we defined that the list contains strings. Now we call your code:

new RentalGeneric(123, mylist)

mylist is a strings list, so RentalGeneric 's type parameter is String too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM