Results 1 to 7 of 7
- 04-22-2008, 11:15 PM #1
Member
- Join Date
- Apr 2008
- Posts
- 2
- Rep Power
- 0
-
Yes you can. Just call add method for different kinds of objects. While getting the object from the vector, you can use instanceof operator to test the type of the object and cast accordingly:
Java Code:Vector v = new Vector(); v.add(new Cat()); v.add(new Dog()); if (v.elementAt(0) instanceof Cat) { Cat cat = (Cat)v.elementAt(0); }"The sole cause of man’s unhappiness is that he does not know how to stay quietly in his room." - Blaise Pascal
- 04-23-2008, 05:42 PM #3
I have the feeling that he might mean array not Vector. But the answer is the same: create an array of Object (Object[]) and add whatever you want to it. When you need them from the array check with instanceof.
Daniel @ [www.littletutorials.com]
Language is froth on the surface of thought
- 04-23-2008, 09:53 PM #4
Member
- Join Date
- Apr 2008
- Posts
- 2
- Rep Power
- 0
Thanks so much!! That's exactly the kind of example I needed. I did mean vector instead of array, I want to use a vector because it grows sort of dynamically where with an array I have to copy things a bunch of times.
Thanks again!
Nathand
- 04-23-2008, 10:26 PM #5
Hi Nathand,
Sorry for making assumptions about what you wanted but I am used to be kind of precise in what I say. I would've say java.util.Vector or at least Vector ;-)
One more comment - usually checking for instanceof is not a sign of a good design. In OOP you have the mechanisms to write generic code that doesn't need to check. It is way better to find a solution that is object oriented and polymorphic. For example in the above example you should strive to make everything you put in the Vector or array derived from a certain class or implementing a certain interface and define the Vector or the array as being of that type using generics. Then when you process the Vector each instance will know what to do on its own. But I am sure you know the theory ;-)Daniel @ [www.littletutorials.com]
Language is froth on the surface of thought
- 04-24-2008, 07:48 AM #6
Generics
You should use Generics when doing this. This way you remove a lot of run time errors to complier errors.
What you should do is.
Java Code:Vector<Object Type> myVector = new Vector<ObjectType>();
- 04-28-2008, 07:55 AM #7
Similar Threads
-
Vectors of Vectors or hash-somethings?
By mindwarp in forum New To JavaReplies: 3Last Post: 03-10-2008, 02:57 PM -
Converting data types
By bluekswing in forum New To JavaReplies: 4Last Post: 01-12-2008, 12:48 AM -
Displaying different image types
By splinter64uk in forum AWT / SwingReplies: 1Last Post: 12-05-2007, 08:12 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks