The Artima Developer Community
Sponsored Link

Java Answers Forum
Searching a vector of objects

2 replies on 1 page. Most recent reply: Feb 24, 2004 3:58 PM by Niall

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Niall

Posts: 10
Nickname: niall
Registered: Feb, 2004

Searching a vector of objects Posted: Feb 23, 2004 6:26 PM
Reply to this message Reply
Advertisement
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


twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: Searching a vector of objects Posted: Feb 23, 2004 7:46 PM
Reply to this message Reply
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.

twc

Niall

Posts: 10
Nickname: niall
Registered: Feb, 2004

Re: Searching a vector of objects Posted: Feb 24, 2004 3:58 PM
Reply to this message Reply
Thanks twc, I have hange the code, but still nothing happens. The statement is not printed or a new object is not created. Any ideas? Cheers.

Flat View: This topic has 2 replies on 1 page
Topic: How To Continue With The Code for Sales Program(Part 2) Previous Topic   Next Topic Topic: connection.setAutoCommit(false) commits after each update?

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use