Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Verifying element types of a Vector Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Verifying element types of a Vector" Watch "Verifying element types of a Vector" New topic
Author

Verifying element types of a Vector

Gavin Bong
Ranch Hand

Joined: Apr 25, 2003
Posts: 56
A vector can contain objects of heterogeneous types.
If I want to write a verification method to ensure that
all its elements are of a certain class; are there any
convenience methods to do this; other then iterating thru it and
checking each individual.
Thanks
G
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1121

Hi Gavin,
As far as I know, the only way is to check each, individual element in the "Vector".
Of-course, you do know that the next release of java (version 1.5, code-named Tiger) will let you create a "Collection" that only contains elements of a certain "Class" (don't you :-)
Good Luck,
Avi.
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
There is an alternative, but even though it is a one line operation you'll end up paying performance and memory penalties. You can call the "toArray(Object[] a)" method to convert the vector elements into an array of a certain type. For example:

In this case every element is a "java.lang.String" and you convert it to a String array. If any of the vector elements wasn't a String, the last line would throw an exception. So by putting the "toArray()" method call inside a try/catch block you can determine if every element is of the same type or not.
If all you care about is checking element types, it's probably better to iterate through the vector instead of doing the "toArray()" method call.
When would I use the "toArray()" method? In some applications you build a list dynamically--by reading elements from a file or database--using a Vector or ArrayList. Once the list is built you may only need to access the list elements, and using an array yeilds better performance than other lists. So you could convert the Vector or ArrayList to an array and performa all your access against the array.
Gavin Bong
Ranch Hand

Joined: Apr 25, 2003
Posts: 56
Avi,
If you're talking about "Generics", yes I have heard of it.
Gavin
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Verifying element types of a Vector
 
Similar Threads
Generic types
Method parameter
quick question about vectors
Vector.add() compiler warning
Using a Vector within a Vector