Reputation: 11452
I have below code snippet - Which doesn't work.
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]);
}
}
Which generates exception is, This...
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)
But this works fine, If I do it like this,
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]);
}
}
Question is, why can't I typecast with Point2D.Double[]?
Upvotes: 2
Views: 1926
Reputation: 53694
because "Object[]" is not an instance of "Point2D.Double[]".
neither of these will work:
Point2D.Double[] = (Point2D.Double[])new Object[0]; // this is essentially what your code is doing
Point2D.Double = (Point2D.Double)new Object();
do this instead:
Point2D.Double[] keys = (Point2D.Double[]) keySet.toArray(new Point2D.Double[keySet.size()]);
Upvotes: 3
Reputation: 354614
Pass a typed array to toArray()
:
Point2D.Double[] keys = keySet.toArray(new Point2D.Double[keySet.size()]);
Upvotes: 1