Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand this use of Java generics

Tags:

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?

like image 998
Niklas Rosencrantz Avatar asked Nov 13 '12 07:11

Niklas Rosencrantz


2 Answers

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 Carobject. 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.

like image 175
Michael Laffargue Avatar answered Oct 26 '22 23:10

Michael Laffargue


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>());
like image 20
Subhrajyoti Majumder Avatar answered Oct 27 '22 01:10

Subhrajyoti Majumder