java泛型和where子句

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

在。net,我可以这样做:

public static T[] CreateAndFillArray<T>(int size) where T : new()
{
   T[] array = new T[size];
   for (int i = size - 1; i >= 0; i--)
       array[i] = new T();
   return array;
}

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

bis0qfac

bis0qfac1#

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

mznpcxlj

mznpcxlj2#

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

anauzrmj

anauzrmj3#

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

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

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

wko9yo5t

wko9yo5t4#

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

import java.lang.reflect.Array;

public class Main
{
    public static void main(String[] args)
    {
        final String[] array;

        array = createAndFillArray(String.class, 10, new StringCreator());

        for(final String s : array)
        {
            System.out.println(s);
        }
    }

    public static <T> T[] createAndFillArray(final Class<T>   clazz,
                                             final int        size,
                                             final Creator<T> creator)
    {
        T[] result = (T[]) Array.newInstance(clazz, size);

        for (int i=0; i<size; i++)
        {
            result[i] = creator.newInstance();
        }

        return result;
    }
}

interface Creator<T>
{
    T newInstance();
}

class StringCreator
    implements Creator<String>
{
    public String newInstance()
    {
        // not the best example since String is immutable but you get the idea
        // you could even have newInstance take an int which is the index of the 
        // item being created if that could be useful (which it might).
        return ("hello");
    }
}

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

ht4b089n

ht4b089n5#

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

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

相关问题