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

时间:2011-08-03 05:04:58

标签: java generics collections

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

8 个答案:

答案 0 :(得分: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> {}

答案 1 :(得分:2)

允许用户创建的自定义类与您的代码一起使用。

假设您发布了支持某种特殊功能的SDK。泛型将允许开发人员在许多地方使用您的功能,几乎任何类。

泛型减少代码重复的目的。

答案 2 :(得分:2)

另一个有趣的用途是在Java的reflection framework中将类型表示为变量。

请特别注意java.lang.Class有一个类型参数,指定Class对象所代表的类。

有关一般信息,请参阅Wikipedia

答案 3 :(得分:1)

还有其他用途,例如泛型类和泛型方法。

答案 4 :(得分:0)

泛型使用:

  • 编译时类型安全。
  • 避免施放(因此避免ClassCastException)。
  • 可读代码。

有关详细说明,请参阅Java Generics tutorial

答案 5 :(得分:0)

枚举是JDK的另一个例子。基本上每当你有两个班级一起工作,但不确切知道哪些类,泛型变得有趣。

答案 6 :(得分:0)

Generic用于创建通用类,因此在创建类时,可以将其设置为参数化类。稍后在创建其对象时,您可以指定类的参数将被类型转换为哪种数据类型或classtype。 此外,它可以使类转换安全,因此只能插入一种数据类型或classtype的元素。这种技术主要用于数据结构类。

答案 7 :(得分:0)

泛型使类型成为参数 泛型使类型(类和接口)在定义类,接口和方法时成为参数。 这就像方法声明中使用的熟悉的形式参数一样。不同之处在于形式参数的输入是值,而类型参数的输入是类型。 示例如下: - 使用形式参数化方法和泛型: -

class Room {

    private Object object;

    public void add(Object object) {
        this.object = object;
    }

    public Object get() {
        return object;
    }
}

public class Main {
    public static void main(String[] args) {
        Room room = new Room();
        room.add(60);
        //room.add("60"); //this will cause a run-time error
        Integer i = (Integer)room.get();
        System.out.println(i);
    }
}

以上的泛型版本: -

class Room<T> {

    private T t;

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

public class Main {
    public static void main(String[] args) {
        Room<Integer> room = new Room<Integer>();
        room.add(60);

        Integer i = room.get();
        System.out.println(i);
    }
}

如果有人添加room.add("60"),则在类的基因版本中,将显示编译时错误。

1.Info source 2. Example taken from