How would I compare two arrays that might have different lengths and get the difference between each array?
For example:
Cat cat = new Cat();
Dog dog = new Dog();
Alligator alligator = new Alligator();
Animal animals[] = { cat, dog };
Animal animals2[] = { cat, dog, alligator };
How would I compare them two arrays and make it return the instance of Alligator?
I would suggest that your question needs to be clarified. Currently, everyone is guessing what about what you are actually asking.
new Cat()“equal”new Cat()? Your example suggests that it does!!Making the assumption that these arrays are intended to be true sets, then you probably should be using
HashSetinstead of arrays, and using collection operations likeaddAllandretainAllto calculate the set difference.On the other hand, if the arrays are meant to represent lists, it is not at all clear what “difference” means.
If it is critical that the code runs fast, then you most certainly need to rethink your data structures. If you always start with arrays, you are not going to be able to calculate the “differences” fast … at least in the general case.
Finally, if you are going to use anything that depends on the
equals(Object)method (and that includes any of the Java collection types, you really need to have a clear understanding of what “equals” is supposed to mean in your application. Are allCatinstances equal? Are they all different? Are someCatinstances equal and others not? If you don’t figure this out, and implement theequalsandhashCodemethods accordingly you will get confusing results.