我有以下代码段 - 无效。
private void startAddingTrackPointValue()
{
Set<Point2D.Double> keySet = this.trackPointList.keySet();
Point2D.Double[] keys = (Point2D.Double[]) keySet.toArray();
for(int i = 0; i < keys.length; i++)
{
System.out.println(keys[i]);
}
}
哪个生成例外,这......
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.awt.geom.Point2D$Double;
at SegmentFactory.startAddingTrackPointValue(SegmentFactory.java:170)
at SegmentFactory.<init>(SegmentFactory.java:44)
at TestClass.main(TestClass.java:8)
但正常,如果我这样做,
private void startAddingTrackPointValue()
{
Set<Point2D.Double> keySet = this.trackPointList.keySet();
Object[] keys = (Object[]) keySet.toArray();
for(int i = 0; i < keys.length; i++)
{
System.out.println(keys[i]);
}
}
问题是,为什么我不能用Point2D.Double []进行类型转换?
答案 0 :(得分:3)
因为“Object []”不是“Point2D.Double []”的实例。
这些都不起作用:
Point2D.Double[] = (Point2D.Double[])new Object[0]; // this is essentially what your code is doing
Point2D.Double = (Point2D.Double)new Object();
改为:
Point2D.Double[] keys = (Point2D.Double[]) keySet.toArray(new Point2D.Double[keySet.size()]);
答案 1 :(得分:1)
将输入的数组传递给toArray()
:
Point2D.Double[] keys = keySet.toArray(new Point2D.Double[keySet.size()]);