2011-10-20 116 views
1

我有一個ArrayList<float[]>其中我在浮動數組存儲一個線,即(x0,y0,x1,y1)的笛卡爾值。我每次使用.contains()函數執行一個浮點數組時,它都會返回false,儘管我可以在調試器中看到它存在。 SO似乎在比較內存參考而不是實際值。任何方式來讓他們比較值?浮動[] ArrayList,無法檢查浮動[]是否包含在ArrayList

public static void main (String[] args) { 
    ArrayList <float[]>drawnLines = new ArrayList<float[]>(); 
    float[] line = new float[4]; 

    line[0] = (float)5; 
    line[1] = (float)12; 
    line[2] = (float)55; 
    line[3] = (float)66; 

    drawnLines.add(line); 

    float[] linea = new float[4]; 

    linea[0] = (float)5; 
    linea[1] = (float)12; 
    linea[2] = (float)55; 
    linea[3] = (float)66; 

    if (drawnLines.contains(linea)) { 
    System.out.println("contians"); 
    } 
    else { 
    System.out.println(" does not contian"); 
    } 
} 

回答

4

這是因爲line.equals(linea)是錯誤的。

你需要用float[]包裝一個類來定義你的意思。

但是,似乎使用像Line這樣的類將是更好的選擇。


public static void main(String[] args) { 
    List<Line> drawnLines = new ArrayList<Line>(); 
    drawnLines.add(new Line(5, 12, 55, 66)); 
    Line linea = new Line(5, 12, 55, 66); 
    if (drawnLines.contains(linea)) 
     System.out.println("contains " + linea); 
    else 
     System.out.println(" does not contain " + linea); 
} 

static class Line { 
    final float x0, y0, x1, y1; 

    Line(float x0, float y0, float x1, float y1) { 
     this.x0 = x0; 
     this.y0 = y0; 
     this.x1 = x1; 
     this.y1 = y1; 
    } 

    @Override 
    public boolean equals(Object o) { 
     if (this == o) return true; 
     if (o == null || getClass() != o.getClass()) return false; 
     Line line = (Line) o; 
     if (Float.compare(line.x0, x0) != 0) return false; 
     if (Float.compare(line.x1, x1) != 0) return false; 
     if (Float.compare(line.y0, y0) != 0) return false; 
     return Float.compare(line.y1, y1) == 0; 
    } 

    @Override 
    public String toString() { 
     return "Line{" + "x0=" + x0 + ", y0=" + y0 + ", x1=" + x1 + ", y1=" + y1 + '}'; 
    } 
} 

打印

contains Line{x0=5.0, y0=12.0, x1=55.0, y1=66.0} 
+0

好嗎?我該如何去在一個類中封裝浮子給我的定義平等嗎? –

+0

現在提供示例。 –

+0

非常感謝!我現在看到Java在做什麼! –

0

你可以編寫自己的功能任務:

boolean listContains(List<float[]> list, float[] arr) { 
    for (float[] elem : list) { 
    if (Arrays.equals(elem, arr)) { 
     return true; 
    } 
    } 
    return false; 
} 

要在代碼中使用它,改變

if (drawnLines.contains(linea)) { 

if (listContains(drawnLines, linea)) { 
0

您需要實現該檢查方法,如果兩個向量的內容都是一樣的:

private static boolean isTheSameVector(float [] vect1, float [] vect2){ 
    if (vect1.length != vect2.length) { 
     return false; 
    } else { 
     for (int i=0; i< vect1.length; i++) { 
      if (vect1[i] != vect2[i]) { 
       return false; 
      } 
     } 
     return true; 
    } 
} 
相關問題