简体   繁体   English

如何将对象数组转换为任意内容类型T(Object [] - > T [])

[英]How to cast an object array to an arbitrary contenttype T (Object[] -> T[])

I wanna make my own Java streams to easily parse some strings. 我想制作自己的Java流来轻松解析一些字符串。 But I can't convert an object array to a T-array. 但是我无法将对象数组转换为T数组。

What I have already tried: 我已经尝试过的:

//  T[]  <-       Object[] 
    arr = (T[]) cache.toArray();

and

    T[] a = new T[6]; // Cannot create a generic array of T
    int index = 0;
    for (T i : arr) {
     a[++index] = i;
    }

Code: 码:

public StreamParser<T> forEach(Consumer<? super T> action) {
        ArrayList<T> cache = new ArrayList<T>();
        for (T i : arr) {
            action.accept(i);
            cache.add(i);
        }
        System.out.println(arr instanceof String[]);
        arr = (T[]) cache.toArray();
        System.out.println(arr instanceof String[]);
        return this;
    }

Output: 输出:

true
false

ArrayList.toArray() always returns exactly Object[] , never some subtype. ArrayList.toArray()总是返回Object[] ,从不返回某个子类型。

For this to work, you need to pass in a T[] or IntFunction<T[]> as a parameter (either to the constructor of StreamParser , or to the method), and use this in the toArray() call: 为此,您需要传入T[]IntFunction<T[]>作为参数(对StreamParser的构造函数或方法),并在toArray()调用中使用它:

arr = cache.toArray(someIntFn.apply(0 /* or cache.size() */));
// Or
arr = cache.toArray(someArray);

You should use the second method toArray taking an extra parameter. 您应该使用第二种方法来获取额外的参数。 Here are the javadoc link: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28java.lang.Object%5B%5D%29 以下是javadoc链接: https//docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28java.lang.Object%5B%5D%29

Regarding the creating of a generic array, here is the trick required to do it: 关于创建通用数组,以下是执行此操作所需的技巧:

public static <T> T[] genArray(Class<T> clazz, int size){
    return (T[]) Array.newInstance(clazz, size);
}

that means an extra step to perform for which you need to have the actual class matching that T parameter 这意味着要执行的额外步骤需要使实际的类与该T参数匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM