devxlogo

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist