0

我正在使用 DB4o,并希望确保在使用如下代码时得到一个唯一的对象:

  public List<Object> getListOfObjects(final Object o){

        List<Object> result = db.query(new Predicate<Object>(){

          @Override
          public boolean match (Object arg0){

             if(arg0.equals(o)){
                return true;
              }
            else{
                return false;
             }
        });

        return result;
      }

List 对象“结果”最好不超过 1 个元素。但是,Java 不可能在不同的运行时(不同的 JVM)创建具有相同身份的对象吗?如果这可能发生,那么它会弄乱我的数据库。

对于 Java 对象是否可以在 JVM 中具有相同的身份,肯定有一个答案。

-亚历克斯

4

1 回答 1

1

If you overwrite the .equals() method of your object, then its easy to have multiple instances of a object which is equals. The whole purpose of the equal() method is to compare two objects about the 'semantic/content" equality. It does not quarantine any uniqueness.

Now if you do not override any equal method, then the object identity is compared. (like using the == operator). The identity is unique in a JVM and there are never two objects with the same identity.

Btw/Offtopic: If you store thousands of object in db4o and use your query, it will be quite slow. More about that here.

于 2013-03-24T01:03:56.240 回答