简体   繁体   English

[Ljava.lang.Object; 无法转换为 java.util.Collection

[英][Ljava.lang.Object; cannot be cast to java.util.Collection

I am trying to implement Array_AGG as CombineFn, Below is my code:我正在尝试将 Array_AGG 实现为 CombineFn,下面是我的代码:

    public static class ArrayAggArray extends Combine.CombineFn<Object, List<Object>, Object[]> {
    @Override
    public List<Object> createAccumulator() {
      return new ArrayList<>();
    }

    @Override
    public List<Object> addInput(List<Object> accum, Object input) {
      accum.add(input);
      return accum;
    }

    @Override
    public List<Object> mergeAccumulators(Iterable<List<Object>> accums) {
      List<Object> merged = new ArrayList<>();
      for (List<Object> accum : accums) {
        merged.add(accum);
      }
      return merged;
    }

    @Override
    public Object[] extractOutput(List<Object> accumulator) {
      return accumulator.toArray();
    }
  }

When I run the tests, I have been getting java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.Collection当我运行测试时,我得到了java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.Collection java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.Collection

I suspect that we cannot create Iterable<List>.我怀疑我们无法创建 Iterable<List>。 Any sort of other help/input will be appreciated.任何其他帮助/输入将不胜感激。

You have a problem in your code, where you are trying to add a List<Object> as an element in the List<Object> collection, that is why you have your error here:您的代码有问题,您试图将List<Object> List<Object>集合中的元素,这就是为什么您在此处出现错误的原因:

@Override
public List<Object> mergeAccumulators(Iterable<List<Object>> accums) {
    List<Object> merged = new ArrayList<>();
    for (List<Object> accum : accums) {
        merged.add(accum);
    }
    return merged;
}

the merged object has a type of List<Object> but your accum has a type of List<Object> as well, so it cannot cast one to another. merged后的 object 具有List<Object>类型,但您的accum也具有List<Object>类型,因此它不能将一个转换为另一个。

Depending on what you want to do, you have to make another loop over the elements of the accum for example:根据您想做什么,您必须对accum的元素进行另一个循环,例如:

@Override
public List<Object> mergeAccumulators(Iterable<List<Object>> accums) {
    List<Object> merged = new ArrayList<>();
    for (List<Object> accum : accums) {
        for (Object o : accum) {
            merged.add(o);
        }
    }
    return merged;
}

or you can use addAll or other methods you want it to do.或者您可以使用addAll或您希望它执行的其他方法。

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

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