still need more help on vectors.
hi all,
i have a vector of objects and each objects has four values in them. is there anyway to access these individual values in a vector. for example one of the objects may consist of a name, boolean, int, double. if i need to can i get access to the int value. also this vector should only have objects with unique names, i have tried the .contains() and .equals() methods but neither seem to work. what would be the best way to go about this?
thanks
[479 byte] By [
rsinyard] at [2007-9-26 6:49:36]

If you want the elements to have "names", try HashMap instead of Vector. (Or use Hashtable for pre-1.2)
As for the other part of your problem, let me see if I understand it. You want to insert an object that has, say an int field of 1 and a String field of "abc". You're not inserting 1 and "abc" into the Vector/HashMap. You're inserting the object that has those member variables. Then, you want to say "Do any of the elements of my Vector/HashMap contain "abc" as a member variable?"
Is this what you're trying to do? You can't do it directly with Vector/HashMap. You'll have to write your own code to either a) iterate over each element and check its member variables or b) maintain a separate structure that keeps track of the contents of elements as the element are added to your main Vector/Hashtable.
jverd at 2007-7-1 16:16:18 >

If I understand you correctly you have something like:
class MyObject
{
public String name;
public boolean flag;
public int val;
public double pct;
}
and then a java.util.Vector contains many of these types of objects. Here is how you would access the internal members of MyObject:
Vector vec = new Vector();
// add a bunch of MyObjects to vec
String name2 = ((MyObject)vec.get(2)).name;
boolean flag2 = ((MyObject)vec.get(2)).flag;
// etc
To check if a vector has an object with a particular name you would do this:
for(int loop = 0; loop < vec.size(); loop++)
{
if( ((MyObject)vec.get(loop)).name.equals("some name") )
{
// do something
}
}
Be careful: if an element in the vector is null ,
you will get some null pointer exceptions so you should really be doing this:
MyObject obj = (MyObject)vec.get(i);
if(obj == null) throw new Exception...
Or, if you are only interested in a particular field to test for equality (i.e. two MyObject's are considered equal if they have the same name string, regardless of their other member values), then you can override the equals() method of the Object class in MyObject :
class MyObject
{
public String name = "";
public boolean flag;
public int val;
public double pct;
public boolean equals(Object o)
{
MyObject mo = null;
try { mo = (MyObject)o; }
catch(ClassCastException cce)
{ return false; }
if(mo.name.equals(this.name))
return true;
return false;
}
} // class MyObject
// now, in your vector you can:
MyObject someName = new MyObject();
someName.name = "some name";
if( vec.contains(someName) ) // uses the equals() method to test equality
{
// do something
}