java泛型和where子句

wlzqhblo  于 2021-06-30  发布在  Java
关注(0)|答案(5)|浏览(385)

在。net,我可以这样做:

  1. public static T[] CreateAndFillArray<T>(int size) where T : new()
  2. {
  3. T[] array = new T[size];
  4. for (int i = size - 1; i >= 0; i--)
  5. array[i] = new T();
  6. return array;
  7. }

我们必须指定“where t:new()”子句。
如何在java中实现它?

bis0qfac

bis0qfac1#

在java中,不能示例化泛型数组(e、 新的t[size]不能工作)这是因为在运行时泛型类型丢失(“擦除”)并且无法恢复。
有什么原因不能使用,例如,new arraylist()?

mznpcxlj

mznpcxlj2#

在java中不能这样做,因为java不支持结构类型检查。
scala确实如此,但它比实现适当的接口慢得多(因为它在内部使用反射来进行函数调用)。scala不允许您对对象的构造函数的形式设置约束。jvm使用类型擦除,因此泛型代码实际上不知道它操作的是什么类型,因此它无论如何也不能构造该类型的新对象。

anauzrmj

anauzrmj3#

java没有等价的构造。包含构造函数的类没有编译时安全性。
您可以在运行时执行此操作,但必须传递非空的t或类作为参数。运行时不保留使用的实际类型参数。

  1. public static <T> T[] createAndFillArray(T sampleObject, int size) throws Exception {
  2. Class<T> klass = sampleObject.getClass();
  3. T[] arr = (T[]) Array.newInstance(klass, size);
  4. for (int i = 0; i < size; i++) {
  5. arr[i] = klass.newInstance();
  6. }
  7. return arr;
  8. }

如果没有公共的无参数构造函数,上面的方法可以工作,但是会抛出一个异常。你不能让编译器强制执行有一个。
编辑:chssply76击败了我,所以我修改了上面的代码,给出了一个示例,您在其中传递了一个实际的对象示例,只是为了展示它是如何完成的。通常在这种情况下,您会传入类,因为sampleobject不在数组中结束。

wko9yo5t

wko9yo5t4#

您可以使用这个想法来解决其他答案中缺少编译时检查的问题:

  1. import java.lang.reflect.Array;
  2. public class Main
  3. {
  4. public static void main(String[] args)
  5. {
  6. final String[] array;
  7. array = createAndFillArray(String.class, 10, new StringCreator());
  8. for(final String s : array)
  9. {
  10. System.out.println(s);
  11. }
  12. }
  13. public static <T> T[] createAndFillArray(final Class<T> clazz,
  14. final int size,
  15. final Creator<T> creator)
  16. {
  17. T[] result = (T[]) Array.newInstance(clazz, size);
  18. for (int i=0; i<size; i++)
  19. {
  20. result[i] = creator.newInstance();
  21. }
  22. return result;
  23. }
  24. }
  25. interface Creator<T>
  26. {
  27. T newInstance();
  28. }
  29. class StringCreator
  30. implements Creator<String>
  31. {
  32. public String newInstance()
  33. {
  34. // not the best example since String is immutable but you get the idea
  35. // you could even have newInstance take an int which is the index of the
  36. // item being created if that could be useful (which it might).
  37. return ("hello");
  38. }
  39. }

这实际上比您描述的c方法更灵活,因为您可以根据需要控制构造函数,而不是简单地调用no arg。

展开查看全部
ht4b089n

ht4b089n5#

除非将t作为参数传入,否则将无法在java中创建泛型“t”类型的数组。

  1. public static <T> T[] createAndFillArray(Class<T> cls, int size) {
  2. T[] result = (T[]) Array.newInstance(cls, size);
  3. for (int i=0; i<size; i++) {
  4. result[i] = cls.newInstance();
  5. }
  6. return result;
  7. }

相关问题