2012-08-24 93 views
0

我使用db4o的使用對象:比較我db4o中的一個對象與其他新對象

public Tra(String x, int y, int z, int pos, Date de, Date de2) 

我收到一個新的對象(電車),我想比較只有三個參數(串x,INT Y, int z)。

因爲其他參數還沒有值。

我使用:

Tra proto = new Tra(trat.getx(),trat.gety(),trat.getz(),0,null,null); 
      ObjectSet result=db4oHelper.db().queryByExample(proto); 
      if(result.equals(tram)){ 
       Log.d(TAG,"already exists"); 
      } 

但沒有工作:(

有誰幫我

回答

0

除非你已經在你的自定義模型類中重寫的行爲,在Java? .equals()的語言實現只在兩個參數實際上是相同的對象(意思是相同的存儲器地址)時返回true,不一定只是等同的。According to the DB4O documentationObjectSet是一個集合,它不可能是與您的定製原型Tra相同的對象。所以你有兩個問題:

  1. 你查詢的值是不正確的。您可能想要執行一些更類似result.getNext().equals(tram)的操作來訪問集合中的實際模型對象(請記住可能有多個對象)。
  2. 如果x,y和z相同,則需要在模型類中自定義實現equals()以表示它們相等。

第二個問題是由這樣的處理:

public class Tra { 

    /* Existing Code */ 

    @Override 
    public boolean equals(Object obj) { 
     if (obj == null) return false; 
     if (obj == this) return true; 

     if (obj instanceof Tra) { 
      Tra param = (Tra) obj; 
      return this.x == param.x 
        && this.y == param.y 
        && this.z == param.z; 
     } 
    } 
} 

HTH