除了制作类型安全的集合之外,java中泛型的使用?

use*_*643 4 java generics collections

我大多使用泛型来制作类型安全的集合.泛型的其他用途是什么?

hak*_*kon 5

我用它来编写一个非常纤薄的DAO层:

/*
  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> {}
Run Code Online (Sandbox Code Playgroud)