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
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.
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.
Joined: Apr 25, 2003
Avi, If you're talking about "Generics", yes I have heard of it. Gavin