Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uses of generics in java other than making type safe collections?

I have mostly used generics to make type safe collections.What are the other uses of generics?

like image 803
user325643 Avatar asked Dec 28 '22 16:12

user325643


2 Answers

I've used it to write a very slim DAO-layer:

/*
  superclass for all entites, a requirement is that they have the 
  same kind of primary key
*/
public abstract class Entity {
}

/*
  superclass for all DAOs. contains all CRUD operations and anything else
  can be generalized
*/
public abstract class DAO<T extends Entity> {

  //assuming full control over the database, all entities have Integer pks.
  public T find(Integer pk) {...}
  public void save(T entity) {...}
  public void remove(T entity) {...}
  etc...

}

/*
  Complete example of an ideal DAO, assuming that there are no special
  operations specific for the Entity.
  Note the absence of any implementation at all.
*/
public class SpecificDAO extends DAO<SpecificEntity> {}
like image 97
hakon Avatar answered Jan 29 '23 13:01

hakon


To allow user-created, custom classes to be used with your code.

Say you release an SDK that enables some kind of special functionality. Generics will allow developers to utilise your functionality in many places, with almost any class.

The purpose of generics to reduce code repetition.

like image 40
foxy Avatar answered Jan 29 '23 12:01

foxy