简体   繁体   中英

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

I am trying to implement Array_AGG as CombineFn, Below is my code:

    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

I suspect that we cannot create 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:

@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.

Depending on what you want to do, you have to make another loop over the elements of the accum for example:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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