Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Verifying element types of a Vector

 
Gavin Bong
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avi,
If you're talking about "Generics", yes I have heard of it.
Gavin
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic