1

I have a loop, which creates objects. The first Object 'myObject' gets Strings from an other class (the class stores strings in an array. I can access the strings through an hashmap). The Object myOtherObject stores myOject. I want to test whether the object attributes are already present in the object before after every loop continuous. If that's the case I don't want to create a new Object of the class MyClass and continue the loop.

MyClass myObject = new MyClass(mysecObject.get("Value"));
MyOtherClass myOtherObject = new MyOtherClass(myObject);

It is very difficult to show you the code of the loop because there are a lot of own methods and objects.

while(true)
{
   someClass l = someOtherObject.myMethod();
   if (l == null) 
   {
     break;
   }

    MyClass myObject = new MyClass(l.get("Value"));
    MyOtherClass myOtherObject = new MyOtherClass(myObject);


    ...adding myOtherObject to an HashMap

  }

Edit: I made some logical mistakes and I apologize for asking a question before I really thought about it. As it has already been mentioned in the comments I have to create the objects befor I can check if the instances are equal or not (of course it works that way). I solved my problem and want to share it with you. I created an HashSet which automatically checks for duplicate entries and put the objects, which are created in the loop, in the HashSet. How simple is that? Thank you guys for your help and understanding. Have a nice day!

Ubuntix
  • 324
  • 4
  • 15

1 Answers1

1

If you want to check if two instances are equal, you need to override equals(Object o) method. For example:

public MyClass {
    // some properties and methods
    public boolean equals(Object o) {
        boolean condition = some_condition_to_check_they_are_equal 
        return condition;
    }
}

And you can call it to check objects equality:

MyClass myObject = new MyClass(mysecObject.get("Value"));
MyOtherClass myOtherObject = new MyOtherClass(myObject); 
if(myObject.equals(myOtherObject )) {
    // They are equals
}
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
  • I know how to check if two instances are equal. I want to do that before i create a new object in case this new object would have the same instances. – Ubuntix Jan 27 '14 at 09:52
  • So check some criteria are there equal or not before creating. Its depends the equality logic of your class. – Ashot Karakhanyan Jan 27 '14 at 10:02