Question

i'm using db4o with objects:

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

I receive a new object (tram) and I want compare only three arguments (String x, int y, int z).

because the other arguments hasn't values yet.

I'm using:

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");
            } 

but doesn't work :(

Does anyone help me?

Was it helpful?

Solution

Unless you have overridden the behavior in your custom model class, the Java language implementation of .equals() only returns true if both parameters are actually the same object (meaning the same memory address), not necessarily just equivalent. According to the DB4O documentation, ObjectSet is a collection, which could not possibly be the same object as your custom prototype Tra. So you have two problems:

  1. The value you are querying against isn't correct. You probably want to do something more like result.getNext().equals(tram) to access the actual model object in the collection (keeping in mind there may be more than one).
  2. You need to have a custom implementation of equals() in your model class to denote that they are equal if x, y and z are the same.

The second issue being handled by something like this:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top