java - 类和父类(super class)数组的有界通配符

标签 java arrays generics superclass

我有一个 Shape 类和一个扩展 Shape 的类 Circle,如下所示:

public class Shape {
  private double area;
  public Shape(double thatArea) {
      this.area = thatArea;
  }

  public double getArea() {
      return this.area;
  }
}

public class Circle extends Shape {
    private double radius;
    public Circle(double radius) {
        super(3.14*radius*radius);
    }

    public double getRadius() {
        return this.radius;
    }
}

假设我创建一个形状数组如下

Shape[] shapes = new Shape[3];
shapes[0] = new Shape(100.0);
shapes[1] = new Circle(5.0);
shapes[2] = new Shape(35.0);

还有像这样按区域过滤的方法

public Shape[] filterByMaxArea(double maxArea) {
    ArrayList<Shape> shapeResult = new ArrayList<>();

    for (Shape s : shapes) {
        if (s.getArea < maxArea) shapeResult.add(s);
    }

    return (Shape[]) shapeResult.toArray();
}

如果我这样调用 filterByMaxArea() 方法

filterByMaxArea(1000); // in order to include the 
circle too

然后编译器抛出一个ClassCastException

Exception in thread "main" java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to [Lmypackage.Shape;
at mypackage.Main.filterByMaxArea(Main.java:74)

代码中第74行是这个

return (Shape[]) shapeResult.toArray();

谁能解释为什么即使 Circle 是 Shape 的子类型并且之前我有一个 Shape 和 Circle 实例数组,转换仍然失败?

P.S 我也试过用有界通配符声明 ArrayList 但没有任何运气。

 ArrayList<? extends Shape> shapeResult = new ArrayList<>();

最佳答案

toArray() 返回 Object[]toArray(T[] a) 有一个重载版本,它将给出所需的结果,像使用它一样

return shapeResult.toArray(new Shape[shapeResult.size()]);

关于java - 类和父类(super class)数组的有界通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309843/

相关文章:

javascript - 如何将函数用作字符串?

java - 通用 EventManager - 在 3 行代码 :-) 后卡住

java - Android Media Player SeekBar 不通过歌曲文件寻找

java - 无法绕过 ClassCastException

c# - CA1819 : Properties should not return arrays. 此规则是否也适用于其他对象?

java - 嵌套循环在 Mastermind 游戏中无法正常工作

c# - 序列化专业列表<>

java - 如何调用具有特定类型参数的通用方法?

java - Equals 枚举类型中的方法

java - java中顺序运行线程