Some Objects Are More Equal Than Others

Some Objects Are More Equal Than Others

A Vector is a convenient tool for keeping track of a set of objects, particularly when you don’t know in advance how many will be in the set. You can find out whether an object is present in the set using one of three methods: contains, indexOf and lastIndexOf. But all three use the object’s equals method to compare it with the members of the Vector. If the object does not have an equals method and relies on the default built into the Object class, then you will be searching for another reference to the same object, instead of an object with the same characteristics. To illustrate this, suppose you have a Vector of Buttons:

 Button okBut = new Button("OK");boolean okHere = yourVector.contains(okBut);

The boolean will always be returned false because the new Button cannot be in the Vector already. Even if there is an existing Button in the Vector with the same caption, it will not be reported, because the Button class inherits its equals method from the Object class. Now suppose you have a Vector of Points:

 Point origin = new Point(0, 0);boolean datum = yourVector.contains(origin);

This boolean will return true if there is a Point in the vector with the same coordinates, because the Point class has an equals method which compares the x and y values of the two Points. Conversely, if you have an existing Point and you want to check whether it is already referenced in the Vector, you would need to work a little harder:

 boolean pointHere = false;for (int i = 0 ; i < yourVector.size() ; i = i + 1) {    if (yourVector.elementAt(i) == yourPoint) {        pointHere = true;        break;    }}

Note that a Vector's removeElement method also relies on the functionality of the object's equals method.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several