Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

dealing with Vector

  Asked By: Daisy    Date: Oct 13    Category: Java    Views: 626

Is it possible to insert elements of no_standard type in a Vector
(example, objects of my own classes).
If yes, what is the rigth way to do the following:
id.elementAt(i).myMethod(){ ex: workers.elementAt(i).getSalary() and
workers.elementAt(i).getName() } Vector workers = new Vector(5);



5 Answers Found

Answer #1    Answered By: Eileen Carr     Answered On: Oct 13

Of cource you can insert  your class' objects.
You should cast the object to its type  to be
able to access that class' methods and so on.


Answer #2    Answered By: Phoebe Brown     Answered On: Oct 13

Vector accepts classes  of Object type, so you can add any object into that.
But when you retrieve object from that Vector, object will be in the form of
Object, so you need to cast it into your custom class. Then you can use that.
for example: ((myclass)id.elementAt(i)).myMethod();

Answer #3    Answered By: Latoya Murray     Answered On: Oct 13

Yes it is possible, but you have to cast the return value:

Worker worker = (Worker)workers.elementAt(i);
int salary = worker.getSalary();

Or you could start using Java 1.5, which has generics:

Vector<Worker> workers = new Vector<Worker>;
int salary = workers.elementAt(i).getSalaray();

Answer #4    Answered By: Shobhana R.     Answered On: Oct 13

1) it would be better to use a Map implementation instead of a List
2) make it using casting :
((YourObject)id.elementAt(i)).myMethod() etc...

Answer #5    Answered By: Carl Woods     Answered On: Oct 13

why u prefer map than list in this case

Didn't find what you were looking for? Find more on dealing with Vector Or get search suggestion and latest updates.