2015-07-13 132 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

相關問題