Vector indexOf

hi, I've a problem with a Vector function: indexOf

It should return the index of frist element found in the vector using "equals" to compare the object:

well, I've wrote a little program to test this fucntion, but it don't works well, why!!?

import java.util.Vector;

publicclass test{

publicstaticvoid main(String[] args){

Vector<MyString> vet =new Vector();

vet.add(new MyString("zero"));

vet.add(new MyString("one"));

vet.add(new MyString("two"));

System.out.println(vet.elementAt(1).equals("one"));//prints true

System.out.println(vet.contains("one"));// prints false

}

}

now, MyString code:

package p1;

publicclass MyString{

public String name;

public MyString(String nome){

name = nome;

}

publicboolean equals(Object o){

if ( ((String)o).equals(name) )returntrue;

returnfalse;

}

}

[2140 byte] By [daiba] at [2007-10-3 11:15:51]
# 1
It works - there is no String "one" inside that Vector, hence it won't return your MyString instance. I assume Vector does an instanceof test first, before calling equals(). You could check the source code to see.
CeciNEstPasUnProgrammeura at 2007-7-15 13:39:59 > top of Java-index,Java Essentials,Java Programming...
# 2
The equals(...) of String does the instanceof. And as we are here, you should override hashCode() when you override equals(...).Mike
bellyrippera at 2007-7-15 13:39:59 > top of Java-index,Java Essentials,Java Programming...
# 3
> The equals(...) of String does the instanceof. Though Vector would bring a result if he filled it with Strings and submitted a MyString instead... Well, nothing worng with that. GIGO I guess.
CeciNEstPasUnProgrammeura at 2007-7-15 13:39:59 > top of Java-index,Java Essentials,Java Programming...
# 4
Yes, I haven't seen this ;). Hope he'll never search MyString into a container of MyString.
bellyrippera at 2007-7-15 13:39:59 > top of Java-index,Java Essentials,Java Programming...
# 5

it works

import java.util.Vector;

public class test {

public static void main(String[] args) {

Vector<MyString> vet = new Vector();

vet.add(new MyString("zero"));

vet.add(new MyString("one"));

vet.add(new MyString("two"));

System.out.println(vet.elementAt(1).equals(new MyString("one"))); //prints true

System.out.println(vet.contains(new MyString("one"))); // prints false

}

}

daiba at 2007-7-15 13:39:59 > top of Java-index,Java Essentials,Java Programming...
# 6
With the code for MyString that you posted initially? Are you sure?Mike
bellyrippera at 2007-7-15 13:39:59 > top of Java-index,Java Essentials,Java Programming...
# 7
yes, canghing with last post
daiba at 2007-7-15 13:39:59 > top of Java-index,Java Essentials,Java Programming...