【问题标题】:How to cast an object array to an arbitrary contenttype T (Object[] -> T[])如何将对象数组转换为任意内容类型 T (Object[] -> T[])
【发布时间】:2019-04-24 12:20:10
【问题描述】:

我想制作自己的 Java 流来轻松解析一些字符串。但我无法将对象数组转换为 T 数组。

我已经尝试过的:

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

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

代码:

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;
    }

输出:

true
false

【问题讨论】:

  • 您正在转换为 T[],然后检查它是否是 String[] 的实例 ... T 是否与 String 匹配?
  • 是的,我做到了: String[] out = new StreamParser() .of(str) .match("'(.*?)'") .parseToArray("[", ":", "]") .forEach(e -> System.out.println(e)) .getArray();

标签: java arrays casting stream content-type


【解决方案1】:

ArrayList.toArray() 总是准确返回 Object[],绝不是某个子类型。

为此,您需要传入T[]IntFunction&lt;T[]&gt; 作为参数(传递给StreamParser 的构造函数或方法),并在toArray() 调用中使用它:

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

【讨论】:

    【解决方案2】:

    你应该使用第二种方法 toArray 带一个额外的参数。 这里是 javadoc 链接:https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28java.lang.Object%5B%5D%29

    关于创建泛型数组,这里是需要的技巧:

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

    这意味着要执行一个额外的步骤,您需要让实际的类与 T 参数匹配

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 2022-11-02
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多