2015-07-13 129 views
-4

我有2个LinkedList,我想通过一个Object将它们传递给另一个类。我试过这段代码,但是得到错误:java.lang.ClassCastException:[D无法转换为java.util.LinkedList将多个LinkedList从一个类传递到另一个类 - Java

第一类:

public class class1{ 
public Object[] method1(LinkedList<Point> xList,LinkedList<Point> yList){ 

xList.add(new Point(10,10)); 
yList.add(new Point(20,10)); 

return new Object[]{xList, yList}; 
} 
} 

二等

public class class2{ 
public void method2(){ 

LinkedList<Point> xPoints = new LinkedList<Point>(); 
LinkedList<Point> yPoints = new LinkedList<Point>(); 

xPoints.add(new Point(20,40)); 
yPoints.add(new Point(15,15)); 

class1 get = new class1(); 
Object getObj[] = get.method1(xPoints,yPoints); 

xPoints = (LinkedList<Point>) getObj[0]; 
yPoints = (LinkedList<Point>) getObj[1]; 
} 

此外,蚀建议写这个 “@SuppressWarnings(” 未登记 “)” 方法1和method2的外部。

+0

你在哪一行得到错误? –

+0

xPoints =(LinkedList )getObj [0]; – Steve

+0

Object!= Object [] – BN0LD

回答

0

目前您的代码不正确编译,因为你不能写

xPoints.add(20,40); 

您应该使用

xPoints.add(new Point(20,40)); 

在它编译并运行正常,没有抛出ClassCastException报道四个地固定在此之后。

请注意,由于您的method1修改了参数提供的列表,所以您不应该返回它。只需使用:

public void method1(LinkedList<Point> xList, LinkedList<Point> yList) { 
    xList.add(new Point(10, 10)); 
    yList.add(new Point(20, 10)); 
} 

public void method2() { 

    LinkedList<Point> xPoints = new LinkedList<Point>(); 
    LinkedList<Point> yPoints = new LinkedList<Point>(); 

    xPoints.add(new Point(20, 40)); 
    yPoints.add(new Point(15, 15)); 

    class1 get = new class1(); 
    get.method1(xPoints, yPoints); 
    // use xPoints and yPoints here: new point is already added 
} 
+0

这不是我想要的。我想将更新版本的LinkedList传回给method2。当我尝试:xPoints =(LinkedList )getObj [0];我得到错误。 – Steve

+0

@Steve,要使用method2中的更新版本,您不必返回它。它在原地更新。你试一试。例如,在调用'method1'后使用'method2'中的'System.out.println(xPoints)',你会看到'xPoints'已经包含了两个点。 –

+0

非常感谢 – Steve

相关问题