I have created a vector of objects called vertices. Each object contains a name, x value and y value. When adding a new object to the vector, I want to check that another object with the same name does not exist before adding the new object. I have tried unsuccessfully with the following code:
for (int i=0; i<vertices.size();i++){
Object vectorObject = vertices.get(i);
Vertex newYourObject;
newYourObject = ((Vertex)vectorObject);
if (newYourObject.name == name)
System.out.println("Cannot add");
else vertices.addElement(new Vertex(name, x, y));
}
name is global, and contains the name part of the object I am currently trying to create. Any help would be great, thanks
Using the double equal (==) will only tell you if the two variable names are referencing the same object in memory. It will NOT tell you if two separate objects are equal in value. For example:
Integer first = new Integer(1);
Integer second = new Integer(1);
if(first == second)
doSomething();
The if statement will be false, even though both Integer objects have a value of 1 because they are NOT in the same place in memory.
To make things work, the Integer class contains an equals method.
if(first.equals(second)) //this will be true
You need to create such a method for your Vertex class.