For this task, I initially tried to add all the cats and dogs to the pets set individually and remove the cats individually as demonstrated in the attached screenshot but the compiler wouldn't accept it. Can someone please tell me why?
Why can't I add to the pets set and remove elements individually?
You must be signed in to leave a comment
29 March 2021, 07:48
If you create an object, when you call its constructor, then it gets saved in your computers main memory. And now imagine it that way, that the constructor returns this memory address. That address again you save in your reference variable (or at least you could), like Cat cat = new Cat(); cat holds the reference variable to your Cat object. And for the simplicity we assume that address is 1000. Now you create a new Cat object and save it in your set result.add(new Cat()); This time you do not save the reference in a variable but again, for the simplicity we assume the address is 1001. When you now try to remove an object like you did with pets.remove(new Cat()); then you create a new Cat object (simplicity!) at address 1002. That address is looked up and no Cat object is found there. And that's OK cause that new cat you're looking for isn't in your set. That's another one.
29 March 2021, 19:24
So the Cat and Dog objects in the add and remove operations are different from the objects in the cats and dogs sets created previously. Is that right?
30 March 2021, 11:35
The references of the Dog and Cat objects you created have been added to the set, not the objects themselves. result.add(new Cat()); new Cat() returns the address where in the memory the object could be found and the add method adds that address to the set. When you try to remove an object, then you pass a reference (address of the object in memory) to the remove method. But new Cat() and new Cat() create two different objects with different addresses in the memory. They may of course have fields that are identical (or no fields at all) so that the objects seem to be equal. Still they are two objects that are stored at different places in memory. I hope it's clearer now ;)
30 March 2021, 22:37
Yes, that's clearer. Thanks.